我是靠谱客的博主 从容摩托,最近开发中收集的这篇文章主要介绍ScheduledExecutorService 根据条件终止调度任务,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

package com.taobao.vcloud.scheduler.job;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ConditionCancelScheduler {

	public static void main(String[] args) throws Exception {

		ConcurrentHashMap<String, Future> futureMap = new ConcurrentHashMap<String, Future>();
		ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3);

		JobTest job_1 = new JobTest("job_1", futureMap);

		Future future = scheduler.scheduleAtFixedRate(job_1, 1, 5, TimeUnit.SECONDS);
		futureMap.put(job_1.getJobId(), future);
		//Thread.sleep(10000);
		JobTest job_2 = new JobTest("job_22", futureMap);

		Future future_2 = scheduler.scheduleAtFixedRate(job_2, 1, 5, TimeUnit.SECONDS);
		futureMap.put(job_2.getJobId(), future_2);
		Thread.sleep(20000);
		
		System.out.println("test over");
		scheduler.shutdown();
	}
}
	public class JobTest implements Runnable {
		private ConcurrentHashMap<String, Future> futureMap;
		private int count = 0;
		private String jobId;

		public JobTest(String jobId,ConcurrentHashMap<String, Future> futureMap){
			this.jobId = jobId;
			this.futureMap = futureMap;
		}
		@Override
		public void run() {
			count++;
			System.out.println("this is " + count);

			if (count > 1) {
				try {
					Future future = futureMap.remove(jobId);
					
					future.cancel(true);
				} finally {
					System.out.println("jobId "+jobId +"had cancel");
				}
			}

		}

		public ConcurrentHashMap<String, Future> getFutureMap() {
			return futureMap;
		}

		public void setFutureMap(ConcurrentHashMap<String, Future> futureMap) {
			this.futureMap = futureMap;
		}

		public String getJobId() {
			return jobId;
		}

		public void setJobId(String jobId) {
			this.jobId = jobId;
		}

}

最后

以上就是从容摩托为你收集整理的ScheduledExecutorService 根据条件终止调度任务的全部内容,希望文章能够帮你解决ScheduledExecutorService 根据条件终止调度任务所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(51)

评论列表共有 0 条评论

立即
投稿
返回
顶部