Java Timed Task Scheduler detailed

Source: Internet
Author: User
Tags terminates

Objective

In the actual project development, in addition to Web applications, SOA services, there is a kind of indispensable, that is scheduled task scheduling. The scene of timed tasks can be said to be very extensive, such as some video sites, after purchasing a member, each day will give members a growth value, the monthly will send some film coupons to members; For example, in the scenario of ensuring final consistency, some comparison work is often made using timed task scheduling, for example, some reports that need to be generated, mail , such as some tasks that require regular cleanup of data. This blog will introduce the system of scheduled task scheduling, will cover the timer, Scheduledexecutorservice, open source Toolkit quartz, as well as the combination of spring and quartz and other content.

JDK Native Timer tool: Timer

Scheduled Task scheduling: Tasks that are performed automatically based on a given point in time, given time interval, and given number of executions.

The timer is located under the Java.util package, which contains and contains only one background thread (Timethread) that schedules the timing of multiple business tasks (timetask).

Four usages of schedule and two usages of scheduleatfixedrate


The core method of the timer

Parameter description:

Task: The tasks to be performed require extends Timetask override run ()

time/firsttime: The time of the first execution of a task

period: The interval of time that a task is executed periodically, in milliseconds

delay: The delay time before the task is performed, in milliseconds

Obviously, through the above description, we can achieve:

How long does the delay take to execute a task, a time to perform a task, a delay for a period of time, and a periodic execution of a task;

Think 1: What happens if time/firsttime the specified time before the current time?

when time equals or exceeds time/firsttime, the task! is executed. in other words, if the time specified by Time/firsttime is before the current time, it will be executed immediately.

What's the difference between thinking about 2:schedule and scheduleatfixedrate?

Scheduleatfixedrate: Each execution time pushes back one period interval for the last task to start , meaning that the next execution time is relative to the point at which the last task started, so the execution time is not deferred, but there is a problem with the task executing concurrently.

Schedule: Each execution time pushes a period interval after the last task is completed , that is, the next execution time is relative to the point at which the last task ended, so the execution time is continually postponed.

Think 3: If an exception occurs when executing a task, does it affect the timing schedule of other tasks?

If Timetask throws RuntimeException, then the timer will stop all tasks running!

Think about some of the flaws in 4:timer?

As mentioned earlier, there is a single thread behind the timer, so the timer has a flaw in managing concurrent tasks: All tasks are scheduled by the same thread, all tasks are serially executed, meaning that only one task can be executed at a time, and the delay or exception of the previous task will affect the subsequent task.

Secondly, some scheduling methods of timer are relatively simple, unable to adapt to the complexity of task scheduling in actual projects.

A simple Demo instance


Timer Demo


Run results

Other ways to focus on the timer

Cancel (): Terminates timer timer, discards all currently scheduled tasks (Timetask also exists cancel () method, but terminates Timetask)

purge (): Removes the canceled task from the timer's task queue and returns the number

JDK thread pool support for scheduled task scheduling: Scheduledexecutorservice

Due to the problem with the timer, JDK5 provides a thread pool-based scheduled Task Scheduler: Scheduledexecutorservice.

Design concept: Each scheduled task is executed by one thread in the thread pool, so the task can execute concurrently and is unaffected by each other.

We look directly at the example:


Scheduling of scheduled tasks based on thread pool

Operation Result:


Result

Scheduled Tasks Big Brother: Quartz

Although Scheduledexecutorservice has improved the thread pool for the timer, it is still unable to meet the complicated schedule task scheduling scenario. So Opensymphony provides a powerful open source task scheduling framework: Quartz. Quartz is a pure Java implementation, and as spring's default scheduling framework, due to Quartz's powerful scheduling function, flexible use, but also has the ability to distribute the cluster, can say quartz, can take care of all scheduled task scheduling!

Architecture of the Quartz


Quartz architecture

First Look at a demo:


Business Job


Quartz

Description:

1, from the code point of view, there are xxxbuilder, xxxfactory, quartz use of the builder, Factory mode, there is a very easy-to-understand chain programming style.

2, Quartz has 3 core concepts: Scheduler (Scheduler), Task (Job&jobdetail), Trigger (Trigger). (a task can be triggered by multiple triggers, a trigger can trigger only one task)

3, note that when scheduler dispatches a job, A new job instance (to be destroyed after dispatch) is actually newinstance by reflection, and the Jobexecutioncontext is passed to the job's Execute method, The job instance accesses the Quartz runtime's environment and the job's own detail data through Jobexecutioncontext.

4, Jobdatamap can mount any data that can be serialized, access is very convenient. It is important to note that both jobdetail and trigger can be associated with each other jobdatamap. Jobdatamap In addition to the above code can be obtained, but also in the Yourjob implementation class, add the corresponding setter method gets.

5, trigger is used to tell the quartz scheduler when to execute, there are 2 common triggers: Simpletrigger (similar to a timer), Crontrigger (similar to Linux crontab).

6, in fact, Quartz will load the Quartz.properties file for some property settings when the scheduler is initialized, such as the properties of the quartz background thread pool (threadcount) , job store settings, and so on. It will be found in the project first, if not found then is the default Quartz.properties file in Quartz.jar.

7, quartz the concept of the presence of listeners, such as tasks before and after the task, add, etc., can easily achieve task monitoring.

Crontrigger Example


Crontrigger

How to style cron expressions


Special symbol Description
Cron-expression

Here are some common examples:

0 * * * * 10:15 per day

0 * *2017 10:15 per day

0 * * *? Every afternoon from 2 to 2:59 per minute.

0 0/5 * *? Every afternoon from 2 to 2:59 (the whole point starts, every 5 minutes trigger)

0 0/5 14,18 * *? Every afternoon from 2 to 2:59, 18 to 18:59 (the whole point starts, every 5 points trigger)

0 0-5 * *? Every afternoon from 2 to 2:05 per minute.

0. * 6L of the last week of the month in Friday 10:15 trigger

0. * 6#3 starts in Friday of the third week of the month

We can easily generate some cron online tools, such as http://www.pppet.net/.

Integration of spring and quartz

In fact, it is convenient to combine quartz with spring, just to make some configuration. Based on 2 different ways:

First, the ordinary class, the normal method, is specified directly in the configuration (Methodinvokingjobdetailfactorybean).

Second, the need to inherit Quartzjobbean, the replication of the specified method (executeinternal) can be.

Then, there are some triggers, scheduler configuration, here no longer introduced, as long as the understanding of the use of native quartz, then the combination of spring and the use will be very simple.

OK, here, scheduled task scheduling is over, Happy weekend!

Java Learning Exchange QQ Group: 589809992 prohibit small talk, non-happy do not enter!

Java Timed Task Scheduler detailed

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.