Java scheduled task scheduling and Java Task Scheduling

Source: Internet
Author: User

Java scheduled task scheduling and Java Task Scheduling
Preface

In actual project development, in addition to Web applications and SOA services, there is also an indispensable class, that is, regular task scheduling. Scheduled tasks can be said to be widely used. For example, for some video websites, after purchasing members, members will be given a growth value every day and some movie Coupons will be given to Members every month; for example, in scenarios that ensure eventual consistency, regular task scheduling is often used for some comparison work, such as some reports and emails that need to be generated at a scheduled time, such as some tasks that need to regularly clean up data. This blog introduces scheduled task scheduling, including Timer, ScheduledExecutorService, open source toolkit Quartz, and the combination of Spring and Quartz.

JDK native timing tool: Timer

Scheduled task scheduling: a task automatically executed based on a given time point, a given interval, and a specified number of executions.

Timer is located under the java. util package, which contains only one background thread (TimeThread) to schedule multiple business tasks at a scheduled frequency.

Four schedule usage and two scheduleAtFixedRate usage


Core Timer Methods

Parameter description:

Task: The task to be executed. extends TimeTask override run () is required ()

Time/firstTime: The time when the first task is executed

Period: Interval between periodic Task execution, in milliseconds

Delay: The delay time before the task is executed, in milliseconds

Obviously, through the above description, we can achieve:

The time after which the task will be executed; the time is specified to execute the task; the time is delayed for a period of time, and the time is specified to periodically execute the task;

Thought 1: If time/firstTime is specified, what will happen before the current time?

When the time is equal to or greater than the time/firstTime, the task will be executed!That is to say, if the time/firstTime specified is before the current time, it will be executed immediately.

Question 2: What is the difference between schedule and scheduleAtFixedRate?

ScheduleAtFixedRate:Each execution time starts from the previous Task and then pushes a period backward.That is to say, the next execution time is relative to the start time of the previous task, so the execution time will not be delayed, but there is a problem of concurrent task execution.

Schedule:Each execution time is a period after the last task is completed.That is to say, the next execution time is later than the last task end time.

Think 3: Will scheduled scheduling of other tasks be affected if an exception occurs during task execution?

If TimeTask throws RuntimeException, Timer stops running all tasks!

Thinking 4: some defects of Timer?

As mentioned above, Timer is a single thread, so Timer has the defect of managing concurrent tasks: all tasks are scheduled by the same thread, and all tasks are executed in serial mode, this means that only one task can be executed at a time, and the latency or exceptions of the previous task will affect subsequent tasks.

Second, some Timer scheduling methods are relatively simple and cannot adapt to the complexity of scheduled task scheduling in the actual project.

A simple Demo instance


Timer Demo

 


Running result

Other Timer Methods

Cancel (): Terminate the Timer and discard all tasks currently scheduled (TimeTask also has the cancel () method, but TimeTask is terminated)

Purge (): Remove canceled tasks from the task queue of the timer and return the number of tasks.

 

JDK supports the thread pool for scheduled tasks: ScheduledExecutorService

Due to Timer problems, JDK5 then provides a thread pool-based scheduled task scheduling: ScheduledExecutorService.

Design Philosophy: each scheduled task is executed by a thread in the thread pool. Therefore, tasks can be executed concurrently without affecting each other.

Let's look at the example:


Scheduled Task Based on Thread Pool

Running result:


Result

 

Scheduled task Eldest Brother: Quartz

Although ScheduledExecutorService improves the thread pool of the Timer, it still cannot meet the complicated scheduling scenario of scheduled tasks. Therefore, OpenSymphony provides a powerful open-source task scheduling framework: Quartz. Quartz is implemented in pure Java and serves as the default scheduling framework of Spring. Thanks to the powerful scheduling function, flexible usage, and distributed cluster capabilities of Quartz, Quartz is launched, you can schedule all scheduled tasks!

Z Architecture


Quartz Architecture

Let's take a look at a Demo:


Business Job

 


Quartz

Note:

1. From the code point of view, there are XxxBuilder and XxxFactory, indicating that Quartz uses the Builder and Factory modes and has a very easy-to-understand chain programming style.

2. Quartz has three core concepts: Scheduler, Job, and Trigger ). (A task can be triggered by multiple triggers. One trigger can only trigger one task)

3. Note that when Scheduler schedules a Job, it will actually reflect a new Job instance of newInstance (destroyed after scheduling) and pass JobExecutionContext to the execute method of the Job, the Job instance accesses the Quartz runtime environment and detailed data of the Job through JobExecutionContext.

4. JobDataMap can load any serialized data for easy access. Note that both JobDetail and Trigger can be associated with JobDataMap. In addition to the above Code, JobDataMap can also be obtained by adding the corresponding setter method in the YourJob implementation class.

5. Trigger is used to tell Quartz when the scheduler executes. There are two common triggers: SimpleTrigger (similar to Timer) and CronTrigger (similar to Linux Crontab ).

6. In fact, Quartz is loaded when the scheduler is initialized. properties file, such as the attributes of the Quartz background thread pool (threadCount) and job storage settings. It will first find it from the project. If it cannot be found, it will use the default quartz. properties file in quartz. jar.

7. Quartz has the concept of listener, such as before and after the task execution and addition of the task, which can be used to conveniently monitor the task.

CronTrigger example


CronTrigger

Writing Cron expressions


Special symbol description
Cron expression

Here are some common examples:

0 15 10 **? *Triggered at every day

0 15 10 **? 2017Triggered at every day on January 1, 2017

 

0*14 **?Triggered every minute from 02:59.

0 0/5 14 **?From 02:59 to every afternoon (triggered every 5 minutes starting from)

0 0/5 **?02:59 pm to PM, PM to PM (triggered every 5 minutes starting from pm)

0 0-5 14 **?Triggered every minute from 02:05.

0 15 10? * 6LTriggered at on Friday of the last week of each month

0 15 10? * 6 #3Triggered on Friday of the third week of every month

We can use Cron online tools such as http://www.pppet.net.

 

Integration of Spring and Quartz

In fact, the combination of Quartz and Spring is very convenient, but it is nothing more than some configuration. There are two methods:

First, the common class and common method are directly specified in the configuration (MethodInvokingJobDetailFactoryBean).

Second, inheritQuartzJobBean, rewrite the specified method (executeInternal.

Then there are some configurations of triggers and schedulers. I will not introduce them here. As long as you understand the use of native Quartz, it will be very easy to combine with Spring.

 

Now, the scheduled task scheduling is over, and you have a good weekend!

 

Java study and exchange QQ group: 589809992 chat prohibited, do not enter!

Related Article

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.