Common implementations of Java timed tasks

Source: Internet
Author: User

There are several common implementations of Java's scheduled tasks:

1) Timer

2) Scheduledthreadpoolexecutor

3) integrated cron Quartz in spring

The next step is to describe how these specific implementations

1. Timer

Using the Java self-contained timing class Java.util.Timer and java.util.TimerTask to achieve the multi-task timing triggering and periodic execution, mainly consists of the following two methods:

void Schedule (timertask task, long delay, long period), void scheduleatfixedrate (timertask task, long delay, long period);

Where delay represents the first execution delay (in milliseconds), and period represents the time interval (in milliseconds) for periodic execution. In particular, it is important to note that the period in both methods are not the same as the start time of the previous execution of the task, but the schedule () method does not have a fixed start time after the Task. , it depends on the execution time of the previous task (if it takes longer than period, the latter execution must wait for execution immediately after the previous execution, so it is not a strict interval); scheduleatfixedrate () The next execution of the method is not affected by the time-consuming effect of the previous execution, so if the previous execution was slow, there could be two concurrent execution scenarios.

The typical usage of a timer is as Follows:

Long delay = 1000l;long period = 5000L; Timer timer = new Timer (); timer.schedule (new timertask () {    @Override public    void Run () {        //TODO auto-generated method Stub    }}, delay, period);

The implementation of the timer needs to rely on the internal task queue Taskqueue with the task thread timerthread, where taskqueue implements the task priority queue in a minimal heap, and TimerThread is a single threaded thread of Execution. So one of the problems is that once the single thread is stuck on a task for some reason, the rest of the execution of the subsequent tasks will be affected.

2. Scheduledthreadpoolexecutor

java.util.concurrent.ScheduledThreadPoolExecutor, which inherits from threadpoolexecutor, can also implement multi-tasking timing triggering and periodic execution, and is typically multithreaded (in the form of a thread pool), and consists of the following two methods:

Scheduledfuture<?> scheduleatfixedrate (Runnable command, long initialdelay, long period, timeunit unit);
Scheduledfuture<?> schedulewithfixeddelay (Runnable command, long initialdelay, long delay, timeunit unit);

Where the Scheduleatfixedrate () method is similar to the schedule () method of the timer, the latter execution is affected by the time-consuming effect of the previous execution; Schedulewithfixeddelay () The period in the method indicates that the start time of the next execution of the task is only worse than the end time of the previous execution, which differs from the Scheduleatfixedrate () method of the timer .

Since Scheduledthreadpoolexecutor inherits from threadpoolexecutor, the elements that make up the core of the thread pool are still the same:

    • int Corepoolsize
    • int Maximumpoolsize
    • Long KeepAliveTime
    • Blockingqueue<runnable> WorkQueue
    • Threadfactory threadfactory
    • Rejectedexecutionhandler Handler

But the difference is that Scheduledthreadpoolexecutor allows custom parameters to include only corepoolsize, threadfactory, and handler, while Maximumpoolsize constant is Integer.max_value,keepalivetime constant for the 0,workqueue constant for the new Delayedworkqueue (), which means that the work queue is actually unbounded, And Maximumpoolsize is useless, corepoolsize is the total number of worker threads (no further increase).

Public scheduledthreadpoolexecutor (int corepoolsize,                                       threadfactory threadfactory,                                       Rejectedexecutionhandler handler) {        Super (corepoolsize, integer.max_value, 0, nanoseconds,              New Delayedworkqueue (), threadfactory, handler);}

Because Scheduledthreadpoolexecutor is a thread pool of multiple threads, it is not easy to get into situations where a time-consuming task causes the remaining scheduled tasks to be difficult to allocate to the thread that cannot be executed. It is therefore more recommended to replace the timer with Scheduledthreadpoolexecutor.

3. Cron Quartz

If It's a spring project, you might want to use cron quartz for more flexibility in timing tasks, and you first need to add a dependency configuration to the pom.xml, as Follows:

<dependency>    <groupId>org.quartz-scheduler</groupId>    <artifactid>quartz</ artifactid>    <version>2.2.1</version></dependency><dependency>    <groupid >org.quartz-scheduler</groupId>    <artifactId>quartz-jobs</artifactId>    <version >2.2.1</version></dependency>

then, write an XML configuration file (such as TIME-TASK.XML) that specifies the timing task class and the corresponding trigger time (there are more than one way to configure it, but it is essentially the same, and only one is provided as a reference):

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE Beans Public "-//spring//dtd bean//en" "http://www.springframework.org/dtd/spring-beans.dtd" ><beans > <!--background Traffic Statistics Timer task Configuration-<bean id= "flowdaemon" class= "com.xxx.stats.service.impl.GetFlowDaemon" > &lt ;/bean> <bean id= "flowdaemondetail" class= "org.springframework.scheduling.quartz.MethodInvokingJobDetailFa        Ctorybean "> <!--false indicates that a new task is opened after the last task has been executed--<property name=" concurrent "value=" false "/>    <property name= "targetObject" ref= "flowdaemon"/> <property name= "targetmethod" value= "execute"/> </bean> <!--scheduling trigger--<bean id= "flowdaemontrigger" class= "org.springframework.scheduling.qu Artz. Crontriggerfactorybean "> <property name=" jobdetail "ref=" flowdaemondetail "/> <property name=" CRO Nexpression "value=" 0 30 0/1 * *? " /> </bean> <!--dispatch Factory--<bean class= "oRg.springframework.scheduling.quartz.SchedulerFactoryBean "> <property name=" triggers "> <list > <ref bean= "flowdaemontrigger"/> </list> </property> &LT;/BEAN&G T;</beans>

This assumes that the timed task is a background traffic statistics task, which is triggered once per hour (configured in Cronexpression) and executed in Com.xxx.stats.service.impl.GetFlowDaemon.execute (), And if the previous task is postponed, the latter task is also deferred (that is, it will not execute concurrently). The benefit of this configuration is that all configurations are done in the XML file without any changes to the Java Code.

Similar to 0 30 0/1 * *? The setting of the timing task time is very rich, support diversified needs, see cron Quartz official Tutorial.

REFERENCES

[1] https://my.oschina.net/pingpangkuangmo/blog/745704

[2] http://www.cnblogs.com/hanganglin/articles/3526240.html

[3] http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/crontrigger.html

[4] https://my.oschina.net/u/2851681/blog/744997

[5] http://www.cnblogs.com/obullxl/archive/2011/07/10/spring-quartz-cron-integration.html

in order to respect the original results, if necessary reprint please indicate the source of this article: http://www.cnblogs.com/fernandolee24/p/5877516.html , hereby thank

Common implementations of Java timed tasks

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.