我有一个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);

}

}

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐