Java implementation method and comparison of several task scheduling (timed task)

Source: Internet
Author: User

In the current WEB application, 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.

Timer

I believe that we are already very familiar with Java.util.Timer, it is the simplest way to implement task scheduling, the following gives a specific example: View source print?

01 Package Com.ibm.scheduler;
02 Import Java.util.Timer;
03 Import Java.util.TimerTask;
04
05 public class Timertest extends TimerTask {
06
07 Private String JobName = "";
08
09 Public Timertest (String jobName) {
10 Super ();
11 This.jobname = JobName;
12 }
13
14 @Override
15 public void Run () {
16 System.out.println ("execute" + jobName);
17 }
18
19 public static void Main (string[] args) {
20 Timer timer = new timer ();
21st Long delay1 = 1 * 1000;
22 Long period1 = 1000;
23 Perform a job1 every 1 seconds after 1 seconds from now
24 Timer.schedule (New Timertest ("Job1"), Delay1, PERIOD1);
25 Long Delay2 = 2 * 1000;
26 Long period2 = 2000;
27 Perform a job2 every 2 seconds after 2 seconds from now
28 Timer.schedule (New Timertest ("Job2"), Delay2, PERIOD2);
29 }
30 }
31 /**
32 Output results:
33 Execute JOB1
34 Execute JOB1
35 Execute JOB2
36 Execute JOB1
37 Execute JOB1
38 Execute JOB2
39 */

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.

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. View Source print?

01 Package Com.ibm.scheduler;
02 Import java.util.concurrent.Executors;
03 Import Java.util.concurrent.ScheduledExecutorService;
04 Import Java.util.concurrent.TimeUnit;
05
06 public class Scheduledexecutortest implements Runnable {
07 Private String JobName = "";
08
09 Public Scheduledexecutortest (String jobName) {
10 Super ();
11 This.jobname = JobName;
12 }
13
14 @Override
15 public void Run () {
16 System.out.println ("execute" + jobName);
17 }
18
19 public static void Main (string[] args) {
20 Scheduledexecutorservice service = Executors.newscheduledthreadpool (10);
21st
22 Long initialDelay1 = 1;
23 Long period1 = 1;
24 Perform a job1 every 1 seconds after 1 seconds from now
25 Service.scheduleatfixedrate (
26 New Scheduledexecutortest ("Job1"), InitialDelay1,
27 PERIOD1, Timeunit.seconds);
28
29 Long initialDelay2 = 1;
30 Long delay2 = 1;
31 Perform a job2 every 2 seconds after 2 seconds from now
32 Service.schedulewithfixeddelay (
33 New Scheduledexecutortest ("Job2"), InitialDelay2,
34 Delay2, Timeunit.seconds);
35 }
36 }
37 /**
38 Output results:
39 Execute JOB1
40 Execute JOB1
41 Execute JOB2
42 Execute JOB1
43 Execute JOB1
44 Execute JOB2
45 */

The above code shows two of the most commonly used scheduling methods in Scheduledexecutorservice scheduleatfixedrate and Schedulewithfixeddelay. 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.

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. View Source Print

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.