Scheduledexecutorservice terminate a scheduled task based on conditions

Source: Internet
Author: User
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&L T
		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;
		}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.