我想运行一个计时器,说30秒后时间到期,怎么办? 有些任务只运行几秒钟然后显示已过期,我该怎么办?
答案 0 :(得分:7)
我建议使用java.util.concurrent
包中的ScheduledExecutorService
,该包具有比JDK中其他Timer
实现更丰富的API。
// Create timer service with a single thread.
ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();
// Schedule a one-off task to run in 10 seconds time.
// It is also possible to schedule a repeating task.
timer.schedule(new Callable<Void>() {
public Void call() {
System.err.println("Expired!");
// Return a value here. If we know we don't require a return value
// we could submit a Runnable instead of a Callable to the service.
return null;
}
}, 10L, TimeUnit.SECONDS);
答案 1 :(得分:4)
30秒后调用actionPerformed方法
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;
public class TimerExample {
public static void main(String args[]) {
new JFrame().setVisible( true );
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println( "expired" );
}
};
Timer timer = new Timer( 30000, actionListener );
timer.start();
}
}
答案 2 :(得分:0)
使用Timer。