我需要每 X
秒执行一次任务。
我知道我可以使用 TimerTask
或 ScheduledThreadPool
但我的问题是该任务取决于状态。
IE。任务在运行 B
中执行的操作取决于运行 A
的结果。
对此进行编码的最佳方法是什么?
也许做一个
while(true){
//do stuff
Thread.sleep(5000);
}
这是我在这里能做的最好的事情吗?
最佳答案
只需在 TimerTask 实现中定义您的状态,然后使用 Timer
:
TimerTask task = new TimerTask ()
{
private int state = 0;
@Override
public void run ()
{
System.out.println ("State is: " + state);
state += 1;
}
};
new Timer ().schedule (task, 0L, 1000L);
这将永远每秒(每 1000L 毫秒)运行一次任务。
关于java - 根据先前运行的结果安排定期任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15089070/