Comparison of several Java implementation methods for task scheduling

Source: Internet
Author: User

Introduction: Overview of the current WEB applications, most applications have the function of task scheduling. This paper introduces several Java implementation methods of task scheduling, including Timer,scheduler, Quartz and Jcron Tab, and compares their advantages and disadvantages to provide valuable reference for programmers who need to develop task scheduling.

Objective

Task scheduling is the automatic execution of a task at a given time interval or given number of executions, based on a given point in time. This paper introduces the Java implementation of four kinds of task scheduling: Timer scheduledexecutor Open Source Toolkit Quartz Open Source Tool Kit Jcrontab

In addition, to combine the implementation of complex task scheduling, this article will also introduce some of the use of Calendar.

Back to the top of the page

Timer

I believe we are already very familiar with Java.util.Timer, it is the simplest way to implement task scheduling, the following gives a specific example:
Listing 1. scheduling tasks using a Timer

/tr>
 package Com.ibm.scheduler; 
 Import Java.util.Timer; 

 Import Java.util.TimerTask; 

 public class Timertest extends TimerTask {private String jobName = ""; 
 Public Timertest (String jobName) {super (); 
 This.jobname = JobName; 
 @Override public void Run () {System.out.println ("execute" + jobName); 
 public static void Main (string[] args) {Timer timer = new timer (); 
 Long delay1 = 1 * 1000; 
 Long period1 = 1000; 
 The Job1 timer.schedule (new Timertest ("Job1"), Delay1, period1) is executed every 1 seconds after 1 seconds from now; 
 Long Delay2 = 2 * 1000; 
 Long period2 = 2000; 
 The Job2 timer.schedule (new Timertest ("Job2"), Delay2, PERIOD2) is executed every 2 seconds after 2 seconds from now; } output:execute job1 Execute job1 Execute job2 Execute job1 Execute job1 execute job2 

The core classes that use timer to implement task scheduling are timer and timertask. Where the Timer is responsible for setting the TimerTask start and interval execution time. The user simply creates a timertask inheriting class, implements its own run method, and throws it to the Timer for execution.

The Timer's design core is a TaskList and a taskthread. The Timer throws the received task into its own TaskList and TaskList sorts it according to the task's initial execution time. TimerThread starts as a daemon when creating a Timer. This thread polls all the tasks, finds a recently performed task, and then sleeps, and TimerThread wakes up and executes the task when it reaches the start point of the most recent task to perform. Then TimerThread updates the last task to perform and continues hibernation.

The advantage of a Timer is simplicity, but since all tasks are scheduled by the same thread, all tasks are serially executed, and only one task can be executed at the same time, and the delay or exception of the previous task will affect the subsequent task.

Back to the top of the page

Scheduledexecutor

Given the Timer's flaws, Java 5 has launched a scheduledexecutor based on thread-pool design. The idea is that each scheduled task is executed by a thread in the thread pool, so the task is executed concurrently and is not interfered with each other. It should be noted that only when the task's execution time arrives will scheduedexecutor actually start a thread, and the rest of the time is scheduledexecutor in the polling state.
Listing 2. Using Scheduledexecutor for task scheduling

				 
 Package Com.ibm.scheduler;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.ScheduledExecutorService;

Import Java.util.concurrent.TimeUnit;

	public class Scheduledexecutortest implements Runnable {private String jobName = "";
		Public Scheduledexecutortest (String jobName) {super ();
	This.jobname = JobName;
	@Override public void Run () {System.out.println ("execute" + jobName);

		public static void Main (string[] args) {Scheduledexecutorservice service = Executors.newscheduledthreadpool (10);
		Long initialDelay1 = 1;
        Long period1 = 1;
				After 1 seconds from now, perform a job1 service.scheduleatfixedrate every 1 seconds (the new Scheduledexecutortest ("Job1"), InitialDelay1,

		PERIOD1, Timeunit.seconds);
		Long initialDelay2 = 1;
        Long delay2 = 1;
				After 2 seconds from now, perform a job2 service.schedulewithfixeddelay every 2 seconds (the new Scheduledexecutortest ("Job2"), InitialDelay2,
	Delay2, Timeunit.seconds); } output:execute job1 Execute JOB1 ExecuteJOB2 Execute JOB1 Execute JOB1 execute JOB2

 

Listing 2 shows two of the most common scheduling methods Scheduleatfixedrate and Schedulewithfixeddelay in Scheduledexecutorservice. Scheduleatfixedrate the time interval for the previous task to start at each execution time, that is, each execution time is: InitialDelay, Initialdelay+period, Initialdelay+2*period, ... ; Schedulewithfixeddelay the time interval for the last task to end at each execution time: InitialDelay, Initialdelay+executetime+delay, Initialdelay+2*executetime+2*delay. This shows that Scheduleatfixedrate is based on fixed time interval for task scheduling, Schedulewithfixeddelay depending on the length of time each task executes, is based on the irregular time interval for task scheduling.

Back to the top of the page

Implement complex task scheduling with Scheduledexecutor and Calendar

Both Timer and Scheduledexecutor can only provide task scheduling based on start time and repetition interval, and can not be qualified for more complex scheduling requirements. For example, set the 16:38:10 to perform tasks every Tuesday. This feature cannot be implemented directly using both Timer and scheduledexecutor, but we can implement this function indirectly with Calendar.
Listing 3. scheduling tasks using Scheduledexcetuor and Calendar

				 
 Package Com.ibm.scheduler;
Import Java.util.Calendar;
Import Java.util.Date;
Import Java.util.TimerTask;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.ScheduledExecutorService;

Import Java.util.concurrent.TimeUnit;

	public class ScheduledExceutorTest2 extends TimerTask {private String jobName = "";
		Public ScheduledExceutorTest2 (String jobName) {super ();
	This.jobname = JobName;
	@Override public void Run () {System.out.println ("date =" +new date () + ", execute" + jobName);  /** * Calculation starts at the current time currentdate, satisfies the condition DayOfWeek, hourofday, * minuteofhour, secondofminite recent time * @return * * Public
		Calendar getearliestdate (Calendar currentdate, int dayofweek, int hourofday, int minuteofhour, int secondofminite) { Calculates the current time of Week_of_year,day_of_week, Hour_of_day, Minute,second, and other field values int currentweekofyear = Currentdate.get (
		Calendar.week_of_year);
		int currentdayofweek = Currentdate.get (Calendar.day_of_week); int currenthour = currentdate.geT (Calendar.hour_of_day);
		int currentminute = Currentdate.get (Calendar.minute);

		int currentsecond = Currentdate.get (Calendar.second);
		If the DayOfWeek in the input condition is less than the dayofweek of the current date, Week_of_year needs to postpone the week Boolean weeklater = false;
		if (DayOfWeek < Currentdayofweek) {Weeklater = true; else if (DayOfWeek = = Currentdayofweek) {//when the input condition is equal to the dayofweek of the current date, if the//hourofday in the input condition is less than the//currenthour of the current date, the
			Week_of_year need to postpone one week if (Hourofday < currenthour) {Weeklater = true; else if (Hourofday = = Currenthour) {//when the input condition is equal to the dayofweek of the current date,//If the M in the input condition Inuteofhour is less than the current date//currentminute, week_of_year need to postpone one week if (Minuteofhour < Currentminute) {weeklater = Tru
				E 
                     else if (Minuteofhour = = Currentsecond) {//when the input condition is dayofweek with the current date, Hourofday, When the minuteofhour is equal, if the//secondofminite in the input condition is less than the currentsecond of the current date, the//Week_of_year need Postpone a week if (Secondofminite < Currentsecond)
					{Weeklater = true; if (weeklater) {//Set week_of_year in current date is postponed for the current week Currentdate.set (Calendar.week_of_year, Currentwee
		Kofyear + 1);
		//Set the Day_of_week,hour_of_day,minute,second in the current date to the value in the input criteria.
		Currentdate.set (Calendar.day_of_week, DayOfWeek);
		Currentdate.set (Calendar.hour_of_day, hourofday);
		Currentdate.set (Calendar.minute, Minuteofhour);
		Currentdate.set (Calendar.second, secondofminite);

	return currentdate; public static void Main (string[] args) throws Exception {ScheduledExceutorTest2 test = new ScheduledExceutorTest2 (
		"Job1");
		Gets the current time Calendar currentdate = Calendar.getinstance ();
		Long Currentdatelong = Currentdate.gettime (). GetTime ();
		System.out.println ("Current Date =" + Currentdate.gettime (). toString ());
		Calculates the most recent execution time that satisfies a condition Calendar earliestdate = test. Getearliestdate (currentdate, 3, 16, 38, 10);
		Long Earliestdatelong = Earliestdate.gettime (). GetTime (); System.out.priNtln ("Earliest Date =" + Earliestdate.gettime (). toString ());
		Calculates the time interval from the current time to the last execution time long delay = Earliestdatelong-currentdatelong;
		The calculation execution cycle is one week long period = 7 * 24 * 60 * 60 * 1000;
		Scheduledexecutorservice service = Executors.newscheduledthreadpool (10);

	Job1 service.scheduleatfixedrate (test, delay, period, timeunit.milliseconds) is executed once every other week, after delay milliseconds from now onwards; } output:current date = Wed Feb 17:32:01 CST Earliest date = Tue Feb 8 16:38:10 CST date = Tue Feb 8 16:3

 8:10 CST, execute job1 Date = Tue Feb 16:38:10 CST, execute JOB1

Listing 3 implements the function of the scheduled task every Tuesday 16:38:10. The core is to calculate the absolute time of the most recent Tuesday 16:38:10 based on the current time, and then to compute the time difference from the current one, as an argument to call the Scheduledexceutor function. The Java.util.calendar function is used to calculate the most recent time. First you need to explain some of the calendar's design ideas. Calendar has the following combinations that uniquely identify a date:

Year + MONTH + day_of_month year 
 + MONTH + week_of_month + day_of_week year 
 + MONTH + day_of_week_in_month + day_o F_week year 
 + day_of_year year 
 + Day_of_week + week_of_year 

The above combination, plus Hour_of_day + MINUTE + SECOND, is a complete time label. This example uses the last combination of methods. Enter as Day_of_week, Hour_of_day, MINUTE, SECOND, and current date, output to a future date that satisfies Day_of_week, Hour_of_day, MINUTE, SECOND and is closest to the current date. The principle of the calculation is to start from the input day_of_week, if less than the current date Day_of_week, you need to go to the week_of_year, the current date of the Week_of_year plus overwrite the old value; if equal to the current day_of_ WEEK, the Hour_of_day is continued, and if greater than the current Day_of_week, the Java.util.calenda calendar.set (field, value) function is called directly to the Day_of_week of the current date, Hour_of_day, MINUTE, SECOND assignment is an input value, and so on, until you compare to SECOND. The reader can choose a different combination to calculate the most recent execution time based on the input requirements.

It can be seen that it is troublesome to implement the task scheduling with the above method, which requires a more perfect task scheduling framework to solve these complicated scheduling problems. Fortunately, open Source Toolkit Quartz and Jcrontab provide strong support for this.

Back to the top of the page

Quartz

Quartz can meet more and more complex scheduling requirements, first let's see how to implement the scheduling schedule for every Tuesday 16:38 with Quartz:
Listing 4. Using Quartz for task scheduling

				 
 Package Com.ibm.scheduler;

Import Java.util.Date;
Import Org.quartz.Job;
Import Org.quartz.JobDetail;
Import Org.quartz.JobExecutionContext;
Import org.quartz.JobExecutionException;
Import Org.quartz.Scheduler;
Import Org.quartz.SchedulerFactory;
Import Org.quartz.Trigger;

Import Org.quartz.helpers.TriggerUtils;  Public class Quartztest implements job {@Override//This method implements the task that needs to be performed public void execute (jobexecutioncontext arg0) throws
				jobexecutionexception {System.out.println ("generating-" + arg0.getjobdetail (). Getfullname () + ", type ="
		+ Arg0.getjobdetail ()-Getjobdatamap (). Get ("type"));
	System.out.println (New Date (). toString ()); public static void Main (string[] args) {try {//Create a scheduler schedulerfactory schedfact = new Org.quartz . Impl.
			Stdschedulerfactory ();
			Scheduler sched = Schedfact.getscheduler ();
			Sched.start (); Create a jobdetail that indicates the name,groupname, and the specific job class name,//The job is responsible for defining the tasks that need to be performed jobdetail Jobdetail = new Jobdetail ("Myjob", "Myjobgroup", Quartztest.class);
            Jobdetail.getjobdatamap (). Put ("type", "full");
			Create a weekly trigger Trigger, indicating how many minutes of the week the Trigger Trigger = Triggerutils.makeweeklytrigger (3, 16, 38);
			Trigger.setgroup ("Mytriggergroup");
			Executes Trigger.setstarttime (new Date ()) from the next second of the current time (triggerutils.getevenseconddate);
			Indicates the name Trigger.setname ("Mytrigger") of the trigger;

		Using Scheduler to associate Jobdetail with trigger, start dispatching task Sched.schedulejob (Jobdetail, Trigger);
		catch (Exception e) {e.printstacktrace (); }} output:generating Report-myjobgroup.myjob, type =full Tue Feb 8 16:38:00 CST Generating

 P.myjob, type =full Tue Feb 16:38:00 CST 2011

Listing 4 very succinctly implements one of these complex task schedules. The core classes of Quartz design include Scheduler, Job, and Trigger. Where the job is responsible for defining the tasks that need to be performed, Trigger is responsible for setting the scheduling policy, Scheduler the two together, and triggers the task to begin execution.

Job

The user only needs to create an inheritance class for the Job and implement the Execute method. Jobdetail is responsible for encapsulating the job and the properties of the job and providing it to Scheduler as a parameter. Each time Scheduler executes a task, it first creates an instance of the job and then invokes the Execute method execution. Quartz does not design a constructor with parameters for the job, so the job's properties need to be stored through additional jobdatamap. Jobdatamap can store any number of key,value pairs, for example:
Listing 5. Assigning Values to Jobdatamap

				 
 Jobdetail.getjobdatamap () ("Mydescription", "My Job description"); 
 Jobdetail.getjobdatamap (). Put ("MyValue", 1998); 
 arraylist<string> list = new arraylist<string> (); 
 List.add ("Item1"); 
 Jobdetail.getjobdatamap (). Put ("myarray", list); 

The data in Jobdatamap can be obtained in the following way:
Listing 6. Gets the value of the Jobdatamap

public class Jobdatamaptest implements JOB {@Override public void execute (jobexecutioncontext context) throws Jobex
		ecutionexception {//Gets instname,groupname from the context and datamap String instname = Context.getjobdetail (). GetName ();
		String groupname = Context.getjobdetail (). Getgroup ();
		Jobdatamap Datamap = Context.getjobdetail (). Getjobdatamap ();
		Obtain Mydescription,myvalue from Datamap and myarray String mydescription = datamap.getstring ("mydescription");
		int myvalue = Datamap.getint ("myvalue"); arraylist<string> myarray = (ARRAYLISTLT;
		strin>) datamap.get ("MyArray"); System.out.println ("Instance =" + Instname + ", group =" + groupname + ", description =" + My

	Description + ", value =" + MyValue + ", array item0 =" + myarray.get (0)); } output:instance = myjob, group = myjobgroup, Description = My job description, value =1998, array item0 = Item1

Trigger

The role of Trigger is to set the scheduling policy. Quartz has designed many types of Trigger, the most common of which are Simpletrigger and Crontrigger.

Simpletrigger is suitable for execution at a specific time, or at a specific time interval at a certain point in time. The above features determine Simpletrigger parameters including Start-time, End-time, repeat count, and repeat interval.

Repeat count is an integer that is greater than or equal to zero, or constant simpletrigger.repeat_indefinitely.

Repeat interval A long integer with a value greater than or equal to zero. When Repeat interval takes a value of zero and Repeat count is greater than zero, the concurrent execution of the task is triggered.

Start-time and Dnd-time take the value of java.util.Date. Priority is given to End-time when End-time and repeat count are specified at the same time. Generally, you can specify End-time and set repeat count to repeat_indefinitely.

Here's how the Simpletrigger is constructed:

Public Simpletrigger (string name, 
                       string Group, 
                       date StartTime, 
                       date endtime, 
                       int repeatcount, 
                       Long Repeatinterval) 

Examples are as follows:

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.