我已经了解了 Timer 和 TimerTask 在 Java 中如何工作的基础知识。我遇到一种情况,我需要生成一个任务,该任务将以固定的时间间隔定期运行,以从数据库中检索一些数据。并且需要根据检索到的数据的值来终止(数据本身正在被其他进程更新)
这是我迄今为止想到的。
public class MyTimerTask extends TimerTask {
private int count = 0;
@Override
public void run() {
count++;
System.out.println(" Print a line" + new java.util.Date() + count);
}
public int getCount() {
return count;
}
}
还有一个具有像这样的 main 方法的类。现在我简单地使用了 15 秒的 sleep 来控制 timerTask 运行的时间。
public class ClassWithMain {
public static void main(String[] args) {
System.out.println("Main started at " + new java.util.Date());
MyTimerTask timerTask = new MyTimerTask();
Timer timer = new Timer(true);
timer.scheduleAtFixedRate(timerTask, 0, 5*10*100);
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Main done"+ new java.util.Date());
}
MyTimerTask 类将因数据库服务调用等而变得更加复杂。
我想要做的是,在主类中,询问timerTask返回的值来指示何时调用timer.cancel()并终止进程。现在,如果我尝试使用 MyTimerTask 的 count 属性,它不起作用。所以当我尝试在 ClassWithMain 中添加这些行时
if (timerTask.getCount() == 5){
timer.cancel();
}
它没有停止该过程。
所以我想知道如何才能完成我想做的事情。
最佳答案
private volatile int count = 0;
最好使用 'volatile'。
在 ClassWithMain 中试试这个:
for(;;) {
if (timerTask.getCount() == 5) {
timer.cancel();
break;
} else{
Thread.yield();
}
}
关于Java 使用任务本身的数据终止计时器任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44297297/