2009-06-17 97 views
9
ActionListener taskPerformer = new ActionListener() { 
    public void actionPerformed(ActionEvent evt) { 
     //...Perform a task... 

     logger.finest("Reading SMTP Info."); 
    } 
}; 
Timer timer = new Timer(100 ,taskPerformer); 
timer.setRepeats(false); 
timer.start(); 

根據文件這個計時器應該觸發一次,但它永遠不會發射。 我需要它射擊一次。爪哇鞦韆定時器

回答

17

這個簡單的程序爲我工作:

import java.awt.event.*; 
import javax.swing.*; 

public class Test { 
    public static void main(String [] args) throws Exception{ 
     ActionListener taskPerformer = new ActionListener() { 
      public void actionPerformed(ActionEvent evt) { 
       //...Perform a task... 

       System.out.println("Reading SMTP Info."); 
      } 
     }; 
     Timer timer = new Timer(100 ,taskPerformer); 
     timer.setRepeats(false); 
     timer.start(); 

     Thread.sleep(5000); 
    } 
} 
+0

真。我從來沒有嘗試沒有GUI的Timer。 – akarnokd 2009-06-17 12:22:13

1

你的任務可能只需要報告結果事件線程(EDT),但確實在後臺線程實際工作中一些週期性的速度。

ScheduledExecutorService確切你想要什麼。只記得通過SwingUtility.invokeLater(...)更新您的用戶界面的狀態

1

我從日誌語句中猜測你正在做某種SMTP操作。我認爲我說的java.swing.Timer適用於與UI相關的定時操作,因此它需要和EDT運行。對於更一般的操作,您應該使用java.util.Timer

本文從JavaDoc中聯 - 用於設置

2

本計劃將很好地工作......

setRepeats(boolean flag)函數調用function(actionPerformed)反覆或者

  1. timer.setRepeats(false) == timer只有一次只調用一次執行操作的方法
  2. timer.setRepeats(true) == timer調用actionPerformed方法反覆基於指定時間

搖擺定時器工作

  1. 做任務一次
  2. 做任務的重複時間

步驟來創建擺動定時器:

  1. 創建的ActionListener
  2. 創建計時器構造,然後通過時間和ActionListener的在
  3. 實現actionPerformed()功能在裏面做你的任務
  4. 使用timer.start()用於啓動計時器構造函數中指定的時間之間的任務,使用timer.stop()對於停止任務

例子:

ActionListener al=new ActionListener(
public void actionPerformed(ActionEvent ae) 
{ 
//do your task 
if(work done) 
    timer.stop();//stop the task after do the work 
} 
); 
Timer timer=new Timer(1000,al);//create the timer which calls the actionperformed method for every 1000 millisecond(1 second=1000 millisecond) 
timer.start();//start the task