Spring-boot Quartz Practice

Source: Internet
Author: User

First, the basic concept of understanding

  Before doing the automated test platform has a requirement, that is, the system at the end of each night to perform a test task, the completion of the implementation of the test results sent through the mail. Requires timed tasks to be configurable at any time, prior to a scenario where Linux uses the crontab timed request system for a task execution interface. Although the corresponding problems can be solved, and some aspects of simple rough, but in the timer configuration is really troublesome, want to solve by the code, so consider using quartz to solve.

Through Google probably understand the basic concept of quartz, know some of the basic elements of quartz (strongly recommended to understand the quartz of the work flow, then hands to practice, will take a lot of detours), quartz mainly has the following three elements:

Scheduler: Scheduler or container, all tasks and triggers are registered in this container.

Jobdetail: An executable task

Trigger: Trigger condition at task

The workflow is primarily to register the Jobdetail and trigger combinations with the scheduler container, and then dispatch the contents of the trigger by scheduler according to Jobdetail.

Second, a simple example

According to the above idea, we do one of the simplest timer tasks, specifically as follows:

1. Create an executable task

ImportOrg.quartz.Job;ImportOrg.quartz.JobExecutionContext;/*** Created by Tangrubei on 2018/3/30.*/ Public classMyjobImplementsJob {@Override Public voidExecute (Jobexecutioncontext context) {//Get Context ContentString data = (string) context.getmergedjobdatamap (). Get ("Data");//Do somethingSystem.out.println (data); }}

2. Create containers and triggers, and register tasks and triggers together in a container

Importorg.quartz.*;Importorg.quartz.impl.StdSchedulerFactory;/*** Created by Tangrubei on 2018/3/30.*/ Public classMyjobtest { Public Static voidMain (string[] args)throwsschedulerexception, interruptedexception {//Creating a container factory classSchedulerfactory schedulerfactory =Newstdschedulerfactory ();//Create a containerScheduler Scheduler =Schedulerfactory.getscheduler ();//Start ContainerScheduler.start ();//Create an executable work taskJobdetail Jobdetail = Jobbuilder.newjob (Myjob.class). Withidentity ("Myfirstjob", "MyGroup"). Build ();//Create a triggerCrontrigger trigger = Triggerbuilder.newtrigger (). Withidentity ("Myfirstjobtriger", "MyGroup"). Withschedule (Cronschedulebuilder.cronschedule ("0/5 * * * *?") . Build ();//set the context for the execution of a taskJobdetail.getjobdatamap (). Put ("Data", "My first job");//tasks and timers registered in the containerscheduler.schedulejob (Jobdetail, Trigger); }}

Third, the project practice:

Back to our initial requirements, we need to implement a timed component that supports adding, deleting, updating tasks and automatically load the configured tasks in the configuration or database when the system starts.

Based on the above simple example, we can easily add, delete, update tasks from the configuration, but only when the project is started to execute these things have not been implemented, This time a little Google will be able to find that we just implement the Applicationlistener interface can be implemented when the project starts to load this timer, directly on the code (my side of the requirement is a task corresponding to a trigger, if a trigger for multiple tasks, Delete and update can not follow my this to write it)

Importorg.quartz.*;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.context.ApplicationListener;Importorg.springframework.context.event.ContextRefreshedEvent;ImportJava.util.HashMap;ImportJava.util.Map;/*** Created by Tangrubei on 2017/2/10.*/ Public classQuartzmanagercomponentImplementsApplicationlistener<contextrefreshedevent> {    PrivateScheduler Scheduler; Private FinalString groupName = "Groupexecute";//Injection Factory class@AutowiredPrivateschedulerfactory schedulerfactory;//execution at system startup@Override Public voidonapplicationevent (Contextrefreshedevent event) {Try {//Initialize ContainerScheduler =Schedulerfactory.getscheduler ();//Start ContainerScheduler.start ();//The initial job context and registration tasks, where you can retrieve tasks from a database or configuration, dynamically loadMap Datamap =NewHashMap (); Datamap.put ("Data", "My Job Time");  This. AddJob ("Myjob", "0/5 * * * * *?", Myjob.class, datamap);//}Catch(schedulerexception e) {e.printstacktrace (); }    }//New Tasks    Pbulic voidAddJob (String jobName, String jobtime, Class jobclassz, map<string, object> DataMap)throwsschedulerexception {jobdetail job=jobbuilder.newjob (JOBCLASSZ). Withidentity (JobName, GroupName). Build (); Crontrigger Trigger=Triggerbuilder.newtrigger (). Withidentity (JobName, GroupName). Withschedule (Cronschedulebuilder.cronsch        Edule (Jobtime)). Build (); if(DataMap! =NULL) {Datamap.foreach (k, v)-{Job.getjobdatamap (). Put (k, v);        });    } scheduler.schedulejob (Job, trigger); }//Delete a task     Public voidDeletejob (String jobName)throwsschedulerexception {triggerkey Triggerkey=Triggerkey.triggerkey (JobName, groupName); if(Triggerkey! =NULL) {//Pause TimerScheduler.pausetrigger (triggerkey);//Remove Timerscheduler.unschedulejob (Triggerkey); Jobkey Jobkey=Jobkey.jobkey (JobName, groupName);//Delete a taskscheduler.deletejob (Jobkey); }    }//Update Task     Public voidUpdatejob (String jobName, String jobtime, Class classz, map<string, object> DataMap)throwsschedulerexception {triggerkey Triggerkey=Triggerkey.triggerkey (JobName, groupName);  This. Deletejob (JobName);  This. AddJob (JobName, Jobtime, Classz, DATAMAP); }}

Source Code Address

  

  

  

Spring-boot Quartz Practice

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.