因此,使用this链接作为参考,是否有人可以建议更优雅的解决方案来取消定期的ScheduledExecutorService任务?
以下是我目前正在做的一个例子:
// do stuff
// Schedule periodic task
currentTask = exec.scheduleAtFixedRate(
new RequestProgressRunnable(),
0,
5000,
TimeUnit.MILLISECONDS);
// Runnable
private class RequestProgressRunnable implements Runnable
{
// Field members
private Integer progressValue = 0;
@Override
public void run()
{
// do stuff
// Check progress value
if (progressValue == 100)
{
// Cancel task
getFuture().cancel(true);
}
else
{
// Increment progress value
progressValue += 10;
}
}
}
/**
* Gets the future object of the scheduled task
* @return Future object
*/
public Future<?> getFuture()
{
return currentTask;
}
答案 0 :(得分:15)
我建议您使用int并自行安排任务。
executor.schedule(new RequestProgressRunnable(), 5000, TimeUnit.MILLISECONDS);
class RequestProgressRunnable implements Runnable {
private int count = 0;
public void run() {
// do stuff
// Increment progress value
progressValue += 10;
// Check progress value
if (progressValue < 100)
executor.schedule(this, 5000, TimeUnit.MILLISECONDS);
}
}