当前位置:   article > 正文

ScheduledExecutorService 根据条件终止调度任务_scheduledexecutorservice 取消

scheduledexecutorservice 取消
  1. package com.taobao.vcloud.scheduler.job;
  2. import java.util.concurrent.ConcurrentHashMap;
  3. import java.util.concurrent.Executors;
  4. import java.util.concurrent.Future;
  5. import java.util.concurrent.ScheduledExecutorService;
  6. import java.util.concurrent.TimeUnit;
  7. public class ConditionCancelScheduler {
  8. public static void main(String[] args) throws Exception {
  9. ConcurrentHashMap<String, Future> futureMap = new ConcurrentHashMap<String, Future>();
  10. ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3);
  11. JobTest job_1 = new JobTest("job_1", futureMap);
  12. Future future = scheduler.scheduleAtFixedRate(job_1, 1, 5, TimeUnit.SECONDS);
  13. futureMap.put(job_1.getJobId(), future);
  14. //Thread.sleep(10000);
  15. JobTest job_2 = new JobTest("job_22", futureMap);
  16. Future future_2 = scheduler.scheduleAtFixedRate(job_2, 1, 5, TimeUnit.SECONDS);
  17. futureMap.put(job_2.getJobId(), future_2);
  18. Thread.sleep(20000);
  19. System.out.println("test over");
  20. scheduler.shutdown();
  21. }
  1. }
  2. public class JobTest implements Runnable {
  3. private ConcurrentHashMap<String, Future> futureMap;
  4. private int count = 0;
  5. private String jobId;
  6. public JobTest(String jobId,ConcurrentHashMap<String, Future> futureMap){
  7. this.jobId = jobId;
  8. this.futureMap = futureMap;
  9. }
  10. @Override
  11. public void run() {
  12. count++;
  13. System.out.println("this is " + count);
  14. if (count > 1) {
  15. try {
  16. Future future = futureMap.remove(jobId);
  17. future.cancel(true);
  18. } finally {
  19. System.out.println("jobId "+jobId +"had cancel");
  20. }
  21. }
  22. }
  23. public ConcurrentHashMap<String, Future> getFutureMap() {
  24. return futureMap;
  25. }
  26. public void setFutureMap(ConcurrentHashMap<String, Future> futureMap) {
  27. this.futureMap = futureMap;
  28. }
  29. public String getJobId() {
  30. return jobId;
  31. }
  32. public void setJobId(String jobId) {
  33. this.jobId = jobId;
  34. }
  35. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/83642
推荐阅读
相关标签
  

闽ICP备14008679号