在C#中,启用计时器后,它会在特定间隔时间内触发一个事件。那么我如何在Java中实现这个功能呢?
我想要创建一个方法,在特定的时间间隔内运行该方法。虽然我知道如何在C#中实现此功能,但并不知道如何在Java中实现。
C#中的代码:
private void timer1_Tick(object sender, EventArgs e)
{
//the method
}
我尝试了Timer
和TimerTask
,但我不确定当其他方法正在运行时这种方法是否会运行。
在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);
new Timer().Schedule(DoSomething, 5000, 1000);
new Timer().Schedule(DoSomething, Timer.GetFutureTime(3), Timer.MILLISECONDS_IN_A_DAY);
delay
:Timer timer = new Timer(DELAY_IN_MILLISECONDS_INT, new ActionListener() {
public void actionPerformed(ActionEvent e) {
//some code here
}
});