如何在我认为完成后停止 ScheduledThreadPoolExecutor 中的任务
2022-09-01 10:32:16
我有一个 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);
}
}