Java Timer Implementation Summary

Source: Internet
Author: User

Preface: There are 3 main implementations of Java timers: JDK components, Spring Task,quartz framework.

1. JDK Components
(1) java.util. TimerTask


Mytimertask.java:

 Public classMytimertaskextendsTimerTask {@Override Public voidrun () {System.out.println ("Mytimertask, now:" +NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"). Format (NewDate ())); } Public Static voidMain (string[] args) {Timer timer=NewTimer (); Timer.schedule (NewMytimertask (), 1000, 1000); //Timer.cancel ();//Stop Scheduler    }}

(2) Java.util.concurrent. Scheduledthreadpoolexecutor (Recommended for use after jdk5.0+)


Myscheduledtask.java:

Public  classimplements  Runnable {  publicvoid  run () { System.out.println (new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"). Format (new     Date ())); }}

Myscheduledexecutor.java:

 Public classMyscheduledexecutor { Public Static voidMain (string[] args) {Scheduledthreadpoolexecutor executor=NewScheduledthreadpoolexecutor (10); Scheduledfuture Future= Executor.schedulewithfixeddelay (NewMyscheduledtask (), 1000, 1000, Timeunit.milliseconds); //Future.cancel (true);//Stop Timer task, timer cannot stop timer task, can only close scheduler//Executor.shutdown ();//Shutdown Scheduler    }}

Comparison: Java.util.concurrent.ScheduledThreadPoolExecutor is more flexible and efficient than java.util.TimerTask.


2. Spring Task
(1) Configuration method implementation
Taskjob.java:

@Service  Public class taskjob {  publicvoid  job1 () {System.out.println(new SimpleDateFormat ("  Yyy-mm-dd HH:mm:ss "). Format (new  Date ())); }}

Spring.xml:

<Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:task= "Http://www.springframework.org/schema/task". .. xsi:schemalocation= "... http://www.springframework.org/schema/taskhttp://www.springframework.org/schema/task/spring-task-3.0.xsd">    <!--Automatic injection of timed task components -    <Context:component-scanBase-package= "XXX" />    <!--defining timed task scheduling policies -    <Task:scheduled-tasks>      <task:scheduledref= "Taskjob"Method= "Job1"Cron= "0/1 * * * *?" />    </Task:scheduled-tasks></Beans>

(2) Implementation of the annotation method
Taskjob2.java:

@Component  Public class  /**  * Once every second   / @Scheduled (cron= "0/1 * * * *?") )  publicvoid  job2 () {System.out.println(new SimpleDateFormat (  "Yyyy-mm-dd HH:mm:ss"). Format (new  Date ())); }}

Spring.xml:

<Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:context= "Http://www.springframework.org/schema/context"Xmlns:task= "Http://www.springframework.org/schema/task". .. xsi:schemalocation= "... http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/ spring-context-3.0.xsdhttp://www.springframework.org/schema/taskhttp://www.springframework.org/schema/task/ Spring-task-3.0.xsd ">    <!--Automatic injection of timed task components -    <Context:component-scanBase-package= "XXX" />    <!--to start a timed task of annotation mode -    <Task:annotation-driven/></Beans>

3. Quartz
Quartz is an open source, very rich timer framework, see: http://www.quartz-scheduler.org/.
Quartz can be used independently or in the spring framework, see: http://projects.spring.io/spring-framework/.

(1) Independent use of quartz (see Quartz official example):
Pom.xml:

<Dependencies>    <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></Dependencies>

Define timed tasks, Myjob.java:

 Public class Implements Job {  publicvoidthrows  jobexecutionexception {System.out.println ( New  SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"). Format (new  Date ())); }}

Scheduling Scheduled Tasks, Myjobsheduler:

 Public classMyjobsheduler { Public Static voidMain (string[] args) {Try{jobdetail Job= Jobbuilder.newjob (MyJob.class). Withidentity ("MyJob"). build (); Trigger Trigger=Triggerbuilder.newtrigger (). Withidentity ("Trigger1", "group1")
. Withschedule (Simpleschedulebuilder.simpleschedule (). Withintervalinseconds (
1). RepeatForever ())
. build (); Scheduler Scheduler
=Stdschedulerfactory.getdefaultscheduler ();      Scheduler.schedulejob (Job, trigger);      Scheduler.start (); } Catch(schedulerexception e) {e.printstacktrace (); }}}

(2) Spring integrated quartz
such as: http://docs.spring.io/spring/docs/5.0.0.M4/spring-framework-reference/htmlsingle/#scheduling-quartz.

"Implementation Comparison"

Implementation method Advantages Disadvantages
JDK components No need to introduce third-party dependencies, flexible control Supports simple task scheduling only, does not support complex scheduled tasks such as date specified
Spring Task Full functionality relative to JDK (simple or complex task scheduling with specified dates), support for annotations and configuration 2 ways Spring 3.x and above are supported, see: Http://www.springframework.org/schema/task, and cannot flexibly control task start or stop.
Quartz Open source, full-featured and powerful (complex task scheduling with simple or specified dates), can be used independently, or integrated with spring must introduce quartz dependencies in the project Quartz dependencies must be introduced in the project.

"Summary of Usage"
1. The EE project
--We recommend using quartz without relying on the spring framework.
--Spring 3.x+ is introduced and spring task is recommended if only simple timed task control is required; otherwise, quartz is recommended.
-in particular, in the Spring Boot project, jdk,spring task or quartz can be flexibly selected on demand.

2. Non-EE project
--Simple scheduled task control, we recommend using the JDK implementation: java.util.concurrent.ScheduledThreadPoolExecutor; otherwise, quartz is recommended.

Attached:Linux crontab

In the Linux environment, you can use the CRONTAB program directly to achieve simple timing tasks, such as the timing of the full amount of backup MySQL database.
See: Https://wiki.archlinux.org/index.php/Cron_ (%e7%ae%80%e4%bd%93%e4%b8%ad%e6%96%87)

Reference
Several implementations of http://gong1208.iteye.com/blog/1773177 spring timed tasks
http://www.cnblogs.com/liuyitian/p/4108391.html Spring cron Expression
http://blog.csdn.net/ethanzhao/article/details/4406017 Linux crontab Command format with detailed examples

Java Timer Implementation Summary

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.