2009-06-17 101 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