Springboot Integrated Quartz Dynamic Timing task

Source: Internet
Author: User
Tags bind
Springboot comes with schedule

The legacy of Springboot less XML configuration, which natively supports multiple timing tasks such as expressions
Note that when the program starts, add @EnableScheduling

@Scheduled (cron= "0/5 * * * * *?")
    public void Job () {
        System.out.println ("Executes every five Seconds");
    }
Why to use quartz

Quartz is easier to manage in multi-tasking situations, enabling dynamic configuration
Execution-time expression:

An example of an expression:
Integrated Quartz

How to build Springboot no longer elaborate on the official website and online tutorials a lot.

Maven Dependency

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

Test Job Class
SCHEDULERQUARTZJOB1 and SCHEDULERQUARTZJOB2 codes are pretty much not listed.

Package com.yvan.quartz.job;

Import Org.quartz.Job;
Import Org.quartz.JobExecutionContext;
Import org.quartz.JobExecutionException;
/**
 * Implementation of the Job interface
 * @author Yvan * * */Public
class SchedulerQuartzJob1 implements job{
    private void before () {
        System.out.println ("task Start Execution");
    }

    @Override public
    void execute (jobexecutioncontext arg0) throws Jobexecutionexception {
        before ();
        System.out.println ("Start:" +system.currenttimemillis ());
        TODO Business
        System.out.println ("End:" +system.currenttimemillis ());
        After ();
    }

    private void After () {
        System.out.println ("task Start Execution");
    }

}

Task Invocation Processing
Split it into two partial instantiation jobs, adding task triggers to the Task Scheduler

    private void StartJob1 (Scheduler Scheduler) throws Schedulerexception {//Jobbuilder instances are built by Jobdetail, Jobdetail Specifies that only instances that implement the job interface//Jobdetail are specific job instances jobdetail Jobdetail = Jobbuilder.newjob (schedulerquartzjob1.class). W
        Ithidentity ("Job1", "group1"). Build ();
        Build a trigger based on an expression cronschedulebuilder Cronschedulebuilder = Cronschedulebuilder.cronschedule ("0/5 * * * *?"); Crontrigger expression trigger inherits from Trigger//Triggerbuilder used to build the trigger instance crontrigger Crontrigger = triggerbuilder.new
        Trigger (). Withidentity ("Job1", "group1"). Withschedule (Cronschedulebuilder). build ();
    Scheduler.schedulejob (Jobdetail, Crontrigger); } private void StartJob2 (Scheduler Scheduler) throws Schedulerexception {Jobdetail Jobdetail = jobbuilder.ne
        Wjob (Schedulerquartzjob2.class). Withidentity ("Job2", "group2"). Build ();
        Cronschedulebuilder Cronschedulebuilder = Cronschedulebuilder.cronschedule ("0 0/5 * * *?"); CroNtrigger Crontrigger = Triggerbuilder.newtrigger (). Withidentity ("Job2", "group2"). Withschedule (cronschedu
        Lebuilder). build ();
    Scheduler.schedulejob (Jobdetail, Crontrigger); }
Provide external methods for dynamic management tasks
    /** * Start performing All Tasks * * @throws schedulerexception */public void Startjob () throws Schedulerexcep
        tion {startJob1 (scheduler);
        STARTJOB2 (scheduler);
    Scheduler.start ();
     }/** * Get job Information * * @param name * @param Group * @return * @throws schedulerexception */public string Getjobinfo (string name, String group) throws Schedulerexception {Triggerkey Triggerkey
        = new Triggerkey (name, group);
        Crontrigger Crontrigger = (crontrigger) scheduler.gettrigger (Triggerkey); Return String.Format ("time:%s,state:%s", Crontrigger.getcronexpression (), Scheduler.gettriggerstate (Trigge
    Rkey). Name ()); /** * Modify the execution time of a task * * @param name * @param Group * @param times * @return * @thr OWS Schedulerexception */Public boolean modifyjob (string name, string group, String time) throws Schedulerexcept Ion {Date date = null;
        Triggerkey Triggerkey = new Triggerkey (name, group);
        Crontrigger Crontrigger = (crontrigger) scheduler.gettrigger (Triggerkey);
        String oldtime = Crontrigger.getcronexpression (); if (!oldtime.equalsignorecase (time)) {Cronschedulebuilder Cronschedulebuilder = cronschedulebuilder.cronsched
            Ule (time); Crontrigger trigger = Triggerbuilder.newtrigger (). Withidentity (name, group). Withschedule (Cronschedule
            Builder). build ();
        Date = Scheduler.reschedulejob (Triggerkey, Trigger);
    } return date! = NULL; }/** * Pause All Tasks * * @throws schedulerexception */public void Pausealljob () throws Schedulere
    xception {scheduler.pauseall (); }/** * Pause a task * * @param name * @param Group * @throws schedulerexception */Publ IC void Pausejob (string name, String group) throws Schedulerexception {Jobkey Jobkey = new Jobkey (Name, group);
        Jobdetail Jobdetail = Scheduler.getjobdetail (Jobkey);
        if (Jobdetail = = null) return;
    Scheduler.pausejob (Jobkey); }/** * Restore All Tasks * * @throws schedulerexception */public void Resumealljob () throws Scheduler
    Exception {scheduler.resumeall (); }/** * Restore a task * * @param name * @param Group * @throws schedulerexception */Publ
        IC void Resumejob (string name, String group) throws Schedulerexception {Jobkey Jobkey = new Jobkey (name, group);
        Jobdetail Jobdetail = Scheduler.getjobdetail (Jobkey);
        if (Jobdetail = = null) return;
    Scheduler.resumejob (Jobkey); }/** * Delete a task * * @param name * @param Group * @throws schedulerexception */Publ
        IC void Deletejob (string name, String group) throws Schedulerexception {Jobkey Jobkey = new Jobkey (name, group); Jobdetail JOBDEtail = Scheduler.getjobdetail (Jobkey);
        if (Jobdetail = = null) return;
    Scheduler.deletejob (Jobkey); }
Full code
Package Com.yvan.quartz;

Import Java.util.Date;
Import Org.quartz.CronScheduleBuilder;
Import Org.quartz.CronTrigger;
Import Org.quartz.JobBuilder;
Import Org.quartz.JobDetail;
Import Org.quartz.JobKey;
Import Org.quartz.Scheduler;
Import org.quartz.SchedulerException;
Import Org.quartz.TriggerBuilder;
Import Org.quartz.TriggerKey;
Import org.springframework.beans.factory.annotation.Autowired;

Import org.springframework.context.annotation.Configuration;
Import Com.yvan.quartz.job.SchedulerQuartzJob1;
Import Com.yvan.quartz.job.SchedulerQuartzJob2; /** * Task Scheduler processing * @author Yvan * */@Configuration public class Quartzscheduler {//Task Scheduler @Autowired Private

    Scheduler Scheduler;  /** * Start performing All Tasks * * @throws schedulerexception */public void Startjob () throws Schedulerexception
        {STARTJOB1 (scheduler);
        STARTJOB2 (scheduler);
    Scheduler.start (); }/** * Get job Information * * @param name * @param Group * @return * @throws schedulerexception */public string Getjobinfo (string name, String group) throws Schedule
        rexception {Triggerkey Triggerkey = new Triggerkey (name, group);
        Crontrigger Crontrigger = (crontrigger) scheduler.gettrigger (Triggerkey); Return String.Format ("time:%s,state:%s", Crontrigger.getcronexpression (), Scheduler.gettriggerstate (Trigge
    Rkey). Name ()); /** * Modify the execution time of a task * * @param name * @param Group * @param times * @return * @thr OWS Schedulerexception */Public boolean modifyjob (string name, string group, String time) throws Schedulerexcept
        Ion {Date date = null;
        Triggerkey Triggerkey = new Triggerkey (name, group);
        Crontrigger Crontrigger = (crontrigger) scheduler.gettrigger (Triggerkey);
        String oldtime = Crontrigger.getcronexpression (); if (!oldtime.equalsignorecase (time)) {Cronschedulebuilder CronschedulebuildER = cronschedulebuilder.cronschedule (time); Crontrigger trigger = Triggerbuilder.newtrigger (). Withidentity (name, group). Withschedule (Cronschedule
            Builder). build ();
        Date = Scheduler.reschedulejob (Triggerkey, Trigger);
    } return date! = NULL; }/** * Pause All Tasks * * @throws schedulerexception */public void Pausealljob () throws Schedulere
    xception {scheduler.pauseall (); }/** * Pause a task * * @param name * @param Group * @throws schedulerexception */Publ
        IC void Pausejob (string name, String group) throws Schedulerexception {Jobkey Jobkey = new Jobkey (name, group);
        Jobdetail Jobdetail = Scheduler.getjobdetail (Jobkey);
        if (Jobdetail = = null) return;
    Scheduler.pausejob (Jobkey); }/** * Restore All Tasks * * @throws schedulerexception */public void Resumealljob () throws Scheduler Exception{Scheduler.resumeall (); }/** * Restore a task * * @param name * @param Group * @throws schedulerexception */Publ
        IC void Resumejob (string name, String group) throws Schedulerexception {Jobkey Jobkey = new Jobkey (name, group);
        Jobdetail Jobdetail = Scheduler.getjobdetail (Jobkey);
        if (Jobdetail = = null) return;
    Scheduler.resumejob (Jobkey); }/** * Delete a task * * @param name * @param Group * @throws schedulerexception */Publ
        IC void Deletejob (string name, String group) throws Schedulerexception {Jobkey Jobkey = new Jobkey (name, group);
        Jobdetail Jobdetail = Scheduler.getjobdetail (Jobkey);
        if (Jobdetail = = null) return;
    Scheduler.deletejob (Jobkey); } private void StartJob1 (Scheduler Scheduler) throws Schedulerexception {//Jobbuilder instance is built by Jobdetail, Jobdet AIL specifies that only instances of the job interface are implemented//Jobdetail is specific Job instance Jobdetail Jobdetail = Jobbuilder.newjob (Schedulerquartzjob1.class). Withidentity ("Job1", "group1"). Build ();
        Build a trigger based on an expression cronschedulebuilder Cronschedulebuilder = Cronschedulebuilder.cronschedule ("0/5 * * * *?"); Crontrigger expression trigger inherits from Trigger//Triggerbuilder used to build the trigger instance crontrigger Crontrigger = Triggerbuild
        Er.newtrigger (). Withidentity ("Job1", "group1"). Withschedule (Cronschedulebuilder). build ();
    Scheduler.schedulejob (Jobdetail, Crontrigger); } private void StartJob2 (Scheduler Scheduler) throws Schedulerexception {Jobdetail Jobdetail = jobbuilder.ne
        Wjob (Schedulerquartzjob2.class). Withidentity ("Job2", "group2"). Build ();
        Cronschedulebuilder Cronschedulebuilder = Cronschedulebuilder.cronschedule ("0 0/5 * * *?"); Crontrigger Crontrigger = Triggerbuilder.newtrigger (). Withidentity ("Job2", "group2"). Withschedule (Cronsch
        Edulebuilder). build (); Scheduler.scheDulejob (Jobdetail, Crontrigger);
 }
}
Scheduler Injection
This is done by listening to the spring container loading complete event, initiating the task call
Handing scheduler to spring initialization management
Package Com.yvan.quartz;
Import Org.quartz.Scheduler;
Import org.quartz.SchedulerException;
Import Org.quartz.SchedulerFactory;
Import Org.quartz.impl.StdSchedulerFactory;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.context.ApplicationListener;
Import Org.springframework.context.annotation.Bean;
Import org.springframework.context.annotation.Configuration;

Import org.springframework.context.event.ContextRefreshedEvent; @Configuration public class Applicationstartquartzjoblistener implements applicationlistener<

    contextrefreshedevent>{@Autowired private Quartzscheduler Quartzscheduler; /** * Initial Start quartz */@Override public void Onapplicationevent (Contextrefreshedevent event) {try
            {quartzscheduler.startjob ();
        SYSTEM.OUT.PRINTLN ("Task has been started ...");
        } catch (Schedulerexception e) {e.printstacktrace (); }}/** * Initial injection Scheduler * @return * @throws schedulerexception */@Bean public Scheduler Scheduler () throws schedulerexception{
        Schedulerfactory Schedulerfactorybean = new Stdschedulerfactory (); 
    return Schedulerfactorybean.getscheduler (); }

}
Encapsulation API
Here the API is designed to facilitate the dynamic management of the task, of course, depending on these interfaces can also do an interface to more intuitive operation of management tasks, this will not repeat.
Package com.yvan.controller.quartzApi;
Import org.quartz.SchedulerException;
Import org.springframework.beans.factory.annotation.Autowired;
Import org.springframework.web.bind.annotation.RequestMapping;

Import Org.springframework.web.bind.annotation.RestController;

Import Com.yvan.quartz.QuartzScheduler; /** * There is no restful style here simply encapsulates the API * * @author Yvan * */@RestController @RequestMapping ("/quartz") public class Qu

    Artzapicontroller {@Autowired private quartzscheduler quartzscheduler;
        @RequestMapping ("/start") public void Startquartzjob () {try {quartzscheduler.startjob ();
        } catch (Schedulerexception e) {e.printstacktrace (); }} @RequestMapping ("/info") Public String getquartzjob (string name, String group) {String info = Nu
        ll
        try {info = quartzscheduler.getjobinfo (name, group);
        } catch (Schedulerexception e) {e.printstacktrace ();
   }     return info; } @RequestMapping ("/modify") Public boolean modifyquartzjob (string name, string group, string time) {Boo
        Lean flag = true;
        try {flag = quartzscheduler.modifyjob (name, group, time);
        } catch (Schedulerexception e) {e.printstacktrace ();
    } return flag;
            } @RequestMapping (value = "/pause") public void Pausequartzjob (string name, string group) {try {
        Quartzscheduler.pausejob (name, group);
        } catch (Schedulerexception e) {e.printstacktrace (); }} @RequestMapping (value = "/pauseall") public void Pauseallquartzjob () {try {QUARTZSC
        Heduler.pausealljob ();
        } catch (Schedulerexception e) {e.printstacktrace ();
            }} @RequestMapping (value = "/delete") public void Deletejob (string name, string group) {try {
      Quartzscheduler.deletejob (name, group);  } catch (Schedulerexception e) {e.printstacktrace ();
 }
    }

}
Run results
Task has started
... 18-03-02 14:39:46,879  INFO Tomcatembeddedservletcontainer:201-tomcat started on port (s): 8080 (http)
  18-03-02 14:39:46,883  INFO start:57-started start in 3.18 seconds (JVM running for 3.47)
  task begins execution
start: 1519972790003
  
    end: 1519972790003 task begins execution start
: 1519972795000
End: 1519972795000
task begins execution
  

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.