我有一个特定的任务,必须定期执行,或者根据条件仅执行一次。我正在使用以下方法:
Runnable r = new Runnable() {
public void run()
{
//Execute task
}
};
final long freq = frequencyOfTask;
ScheduledExecutorService dataTimer = Executors.newScheduledThreadPool(1);
ScheduledFuture<?> dataTimerHandle = dataTimer.scheduleAtFixedRate(r, 0L, freq, TimeUnit.MILLISECONDS);
if(!isDynamic)
{
dataTimerHandle.cancel(false); //cancel the event in main thread while asking the already submitted tasks to complete.
}
在 isDynamic
为 false
(即任务未取消)的情况下,任务运行良好。但是,对于另一种情况(当需要执行仅一次时),它根本不执行。
最佳答案
它不会执行,因为您在任务有机会运行一次之前就取消了任务 - scheduleAtFixedRate
将立即返回并允许您的方法继续执行,这是它所做的第一件事是取消尚未执行的任务。
不要安排任务然后取消它,只需将其作为非计划任务提交即可,例如
ScheduledExecutorService dataTimer = Executors.newScheduledThreadPool(1);
if(isDynamic)
{
dataTimer.scheduleAtFixedRate(r, 0L, freq, TimeUnit.MILLISECONDS);
}
else
{
dataTimer.submit(r);
}
在后一种情况下,任务将只执行一次。
关于java - 根据条件定期或仅运行一次 ScheduledExecutorService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29137887/