java停止任务_java – 一旦我认为它完成,如何在ScheduledThreadPoolExecutor中停止任务...
我有一个ScheduledThreadPoolExecutor,我计划任务以固定的速率运行.我希望任务以指定的延迟运行,最多为10次,直到“成功”为止.之后,我不想让任务重试.所以基本上我需要停止运行计划的任务,当我想要停止它,但不关闭ScheduledThreadPoolExecutor.任何想法我该怎么做?
这里有一些伪代码 –
public class ScheduledThreadPoolExecutorTest
{
public static ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(15); // no multiple instances, just one to serve all requests
class MyTask implements Runnable
{
private int MAX_ATTEMPTS = 10;
public void run()
{
if(++attempt <= MAX_ATTEMPTS)
{
doX();
if(doXSucceeded)
{
//stop retrying the task anymore
}
}
else
{
//couldn't succeed in MAX attempts, don't bother retrying anymore!
}
}
}
public void main(String[] args)
{
executor.scheduleAtFixedRate(new ScheduledThreadPoolExecutorTest().new MyTask(), 0, 5, TimeUnit.SECONDS);
}
}
更多推荐
所有评论(0)