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
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
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:
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
First Look at a demo:
Description
1, from the code point of view, there are xxxbuilder, xxxfactory, quartz used to 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, and a trigger can trigger only one task)
3, note when the scheduler dispatching job, in fact, through reflection newinstance a new job instance (to be dispatched after the completion of the destruction), at the same time will jobexecutioncontext pass to the job of the Execute method, The job instance accesses the Quartz runtime's environment and the job's own detail data through Jobexecutioncontext.
4, Jobdatamap can be loaded any data 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 used to tell the quartz scheduler when the execution, commonly used triggers have 2 kinds: simpletrigger (like a timer), Crontrigger (similar to Linux crontab).
6, in fact, quartz in the scheduler initialization, will load the Quartz.properties file for some property settings, such as quartz background thread pool properties (threadcount), job storage 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 existence listener concept, such as the task before and after the addition of tasks, can facilitate the implementation of task monitoring.
Crontrigger Example
Here are some common examples:
0 to ten ? * Triggered 10:15 Daily
0 to ten ? 2017 2017 daily 10:15 Trigger
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 15 10? * 6L of the last week of the month of Friday 10:15 Trigger
0 15 10? * 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.
Java Timed Task Scheduler detailed