一旦我认为它已经完成,如何在ScheduledThreadPoolExecutor中停止任务 [英] How to stop a task in ScheduledThreadPoolExecutor once I think it's completed
问题描述
我有一个ScheduledThreadPoolExecutor,我用它来安排以固定速率运行的任务。我希望任务以指定的延迟运行最多10次,直到它成功。在那之后,我不希望重试任务。所以基本上我需要停止运行计划任务,当我希望它被停止时,但不关闭ScheduledThreadPoolExecutor。知道我该怎么做吗?
I have a ScheduledThreadPoolExecutor with which I schedule a task to run at a fixed rate. I want the task to be running with a specified delay for a maximum of say 10 times until it "succeeds". After that, I will not want the task to be retried. So basically I'll need to stop running the scheduled task when I want it to be stopped, but without shutting down the ScheduledThreadPoolExecutor. Any idea how I'd do that?
这里有一些伪代码 -
Here's some pseudocode -
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);
}
}
推荐答案
运行此测试,打印 1 2 3 4 5
并停止
run this test, it prints 1 2 3 4 5
and stops
public class ScheduledThreadPoolExecutorTest {
static ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(15); // no
static ScheduledFuture<?> t;
static class MyTask implements Runnable {
private int attempt = 1;
public void run() {
System.out.print(attempt + " ");
if (++attempt > 5) {
t.cancel(false);
}
}
}
public static void main(String[] args) {
t = executor.scheduleAtFixedRate(new MyTask(), 0, 1, TimeUnit.SECONDS);
}
}
这篇关于一旦我认为它已经完成,如何在ScheduledThreadPoolExecutor中停止任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!