java – 一旦我认为它完成,如何在ScheduledThreadPoolExecutor中
发布时间:2020-12-14 16:35:44 所属栏目:Java 来源:网络整理
导读:我有一个ScheduledThreadPoolExecutor,我计划任务以固定的速率运行.我希望任务以指定的延迟运行,最多为10次,直到“成功”为止.之后,我不想让任务重试.所以基本上我需要停止运行计划的任务,当我想要停止它,但不关闭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(),5,TimeUnit.SECONDS); } } 解决方法
运行此测试,打印1 2 3 4 5并停止
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(),1,TimeUnit.SECONDS); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |