[英]Equivalent of Timer in C# in Java?
在C#中,计时器将在启用时以特定间隔触发事件。 我如何用Java实现这一目标?
我想让一个方法以特定的间隔运行。 我知道如何在C#中执行此操作,但不知道Java。
C#中的代码:
private void timer1_Tick(object sender, EventArgs e)
{
//the method
}
我尝试过Timer
和TimerTask
,但我不确定该方法是否会在其他方法运行时运行。
一种方法是使用ExecutorService :
Runnable task = new Runnable() {
@Override
public void run() {
// your code
}
};
ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
service.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.Seconds);
您可以使用codeplex库来实现此目的。
安排任务以每秒运行一次,初始延迟为5秒
new Timer().Schedule(DoSomething, 5000, 1000);
安排任务每天凌晨3点运行
new Timer().Schedule(DoSomething, Timer.GetFutureTime(3), Timer.MILLISECONDS_IN_A_DAY);
您可以使用javax.swing.Timer 。 它在构造函数中有delay
:
Timer timer = new Timer(DELAY_IN_MILLISECONDS_INT, new ActionListener() {
public void actionPerformed(ActionEvent e) {
//some code here
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.