Let's talk about it. Apricot Color Platform Rental QQ2952777280 "Words Fairy Source Forum" hxforum.com "Papaya Source Forum" papayabbs.com The issue of this article, this time particularly uncomfortable, maybe some students have encountered. In fact, it can be said that it is a trivial matter, but the feeling is also not to be ignored. I just graduated from the company, every time each submission code has strict specifications, such as table and space indentation have strict requirements, you can say that you do not comply with the development specifications are equivalent to the online bug problem, or more serious. Now find out that the company is really not so important to this unimportant but particularly important question ah, ah ah ah ah Ah!!!
What is a dynamic configuration timer task?
Return to the point, say this topic, dynamic configuration. The students who have not been in touch with a timed task can read this article: several ways to implement Java timed tasks
The implementation of the timing task thousands of thousands of people, but the basis of the 1, the JDK Timer Class 2, Quartz 3, Springtask. I have used three ways of production. But the most common use in the process is the way XML is configured, the simplest way, no code intrusion, but also better understanding.
But there is a fatal disadvantage, such as you want to change the trigger time of a task, or you want to add a task, pause a task. What do you do?
Stop the App! Change the XML Configuration! Re-boot!
is not very deadly. Recently re-study the configuration of the next quartz, to achieve a non-stop add, pause, delete, immediately trigger the task of the method, in this article to share, in fact, is not a complete study, in the home company has been realized, this is also based on the understanding of the big guy re-implementation.
International Practice ~ First Look at PS: At the end of the article has eggs Oh ~ ~
Management interface:
: Really don't know what to run, every 10 seconds to play a word
Technology implementation
Maven Dependency
Frame support with Springboot
Copy Code
org.quartz-scheduler quartz 2.2.1 org.springframework spring-context-support Copy Code data table copy Code CREATE TABLE ' Sys_task ' (' ID ' bigint () not null auto_increment, ' job_name ' varchar (255) DEFAULT NULL COMMENT ' Task name ', ' description ' varchar (255) default NULL COMMENT ' task description ', ' cron_expression ' varchar (255) default null COMMENT ' cron table Bean_class ', ' 255 ', ' varchar ', default null COMMENT ' task execution when calling which class's method package name + class name ', ' job_status ' varchar (255) default NULL COMMENT ' Task status ', ' job_group ' varchar (255) default NULL COMMENT ' task group ', ' create_user ' varchar (+) default null COMMENT ' Creator ', ' creat E_time ' datetime default NULL COMMENT ' creation time ', ' update_user ' varchar (+) default null COMMENT ' Updater ', ' Update_time ' datetime Default NULL COMMENT ' Update Time ', PRIMARY KEY (' id ')) engine=myisam auto_increment=32 DEFAULT Charset=utf8; Copy Code implementation step ① Start Project, start Ta SK Listener ② reads the database, loads the open task job and trigger into the Scheduler scheduler ③ runs the job class according to the task schedule ④ each run utilizes adaptablejobfactory to instantiate the job class, In order to inject the service to be run Listen is not very simple, but still confused, and listen to me slowly ~ ~ Code Logic First step: Start the project, load monitoring Quartz configuration Springboot configuration method, Regular spring projects can configure replication code in XML @configurationpublic class Quartzconfigration {@Autowired private JOBFACtory jobfactory; @Bean public Schedulerfactorybean Schedulerfactorybean () {Schedulerfactorybean Schedulerfactorybean = new Schedulerfactorybean (); try {schedulerfactorybean.setoverwriteexistingjobs (true); Schedulerfactorybean.setquartzproperties ( Quartzproperties ()); Schedulerfactorybean.setjobfactory (jobfactory); } catch (Exception e) {e.printstacktrace ();} return Schedulerfactorybean; }//Specify Quartz.properties, you can configure the related properties in the configuration file @Bean public properties Quartzproperties () throws IOException { Propertiesfactorybean Propertiesfactorybean = new Propertiesfactorybean (); Propertiesfactorybean.setlocation (New Classpathresource ("/config/quartz.properties")); Propertiesfactorybean.afterpropertiesset (); return Propertiesfactorybean.getobject (); }//Create schedule @Bean (name = "Scheduler") Public Scheduler Scheduler () {return Schedulerfactorybean (). Getscheduler ();}} Copy Code Listener Copy Code @component@order (value = 1) public class Schedulejobinitlistener implements Commandlinerunner {@Autowired Taskservice schedUlejobservice; @Override public void Run (String ... arg0) throws Exception {try {schedulejobservice.initschedule ();} catch (Exception E ) {e.printstacktrace ();}}} The copy code commandlinerunner a Applicationlistener listener similar to the spring framework. The official explanation was: Interface used to indicate, a bean should run when it was contained within a springapplication. Multiple Commandlinerunner beans can be defined within the same application context and can be ordered using the ordered I Nterface or Order @Order annotation. The interface is used as a function to execute its run method when it is added to the spring container. Multiple Commandlinerunner can be executed concurrently in the same spring context and the order of execution is consistent with the order annotation's parameter sequence. Second step: Read the database, load the Scheduler Scheduler job method copy code @Override public void Initschedule () throws Schedulerexception {//Here Get task Information data List Joblist = Taskmapper.list (); for (Taskdo task:joblist) {if (JobStatusEnum.RUNNING.getCode (). Equals (Task.getjobstatus ())) {Quartzmanager.addjob ( Task); }}}} Copy code add task to Quartz Scheduler copy Code/** * Add Task */@SuppressWarnings ("unchecked") public void AddJob (Taskdo Task) {try {//Create Jobde Tail instance, bind job implementation class//Specify the name of the job, the name of the group, and the binding job class Jobclass = (Class ) (Class.forName (Task.getbeanclass ()). Newinstance (). GetClass ()); Jobdetail Jobdetail = Jobbuilder.newjob (Jobclass). Withidentity (Task.getjobname (), Task.getjobgroup ())// Task name and group compose task key. Build (); Define the dispatch trigger rule//Use Corntrigger rule Trigger Trigger = Triggerbuilder.newtrigger (). Withidentity (Task.getjobname (), Task.getjobgroup ())//Trigger key. StartAt (Datebuilder.futuredate (1, Intervalunit.second)). Withschedule ( Cronschedulebuilder.cronschedule (Task.getcronexpression ())). Startnow (). build (); Register the jobs and triggers in the Task Scheduler Scheduler.schedulejob (Jobdetail, Trigger); Start if (!scheduler.isshutdown ()) {Scheduler.start ();}} catch (Exception e) {e.printstacktrace ();}} Copy Code Scheduler as the core scheduler of quartz, there are nearly 50 API interfaces, including task additions, pauses, restores, deletions and a series of APIs, here only to introduce some of the commonly used, want to learn more can later look at the Easter egg section. 1, Start () method: Only after the start () method is called, the scheduler thread starts the trigger trigger, runs JOB2, Pausejob (Jobkey jobkey): Pauses the job based on the specified Jobdetail key. 3, Resumejob (Jobkey jobkey): Restore a job based on the specified key. 4, Deletejob (Jobkey jobkey): Delete a job5, triggerjob (Jobkey jobkey): Triggers a jobdetail (now executed). 6, Reschedulejob (TRiggerkey Triggerkey, Trigger newtrigger): Deletes the trigger with the given key and stores the new trigger, which must be associated with the same job (the new trigger must have the specified job name and group)-however, The new trigger does not have to have the same name as the old trigger. Step three: Run the job class according to the task schedule in fact this step is not required by us, after we load the correct jobdetail and Trigger expressions into the Task Scheduler, the scheduler will automatically trigger the execution of the task Fourth step: Instantiate the Job class, Inject the Service factory class that you want to run copy code @componentpublic class Jobfactory extends Adaptablejobfactory {//This object spring will automatically inject us in, Also belongs to the Spring Technology category. Why do you need this class, in my writing this demo, you can delete this category, found that the program can also run correctly, but why do I add it. You can see our task class, you can see the Job Object instantiation process is carried out in the quartz, this time we will inject the spring stuff in, certainly does not work, so need this class @Autowired private Autowirecapablebeanfactory capablebeanfactory; @Override protected Object Createjobinstance (Triggerfiredbundle bundle) throws Exception {//Call the parent class method Object Jobinstance = Super.createjobinstance (bundle); To inject Capablebeanfactory.autowirebean (jobinstance); return jobinstance; }} Copy code task class copy code @disallowconcurrentexecution//Job not concurrent @componentpublic class Helloworldjob implements job{@Override public void execute (jobexecutioncontext arg0) throws Jobexecutionexception {System.out.println ("Welcome to Yyblog, this is a timed task- -Small Sell"The room was very old." + Dateutils.fulltime (new Date ())); }} Copy the code well, done, a simple dynamic configuration of the scheduled task has been completed. is not so easy, let's try to implement some of the other common APIs. Pause a job public void Pausejob (Taskdo task) throws schedulerexception {Jobkey Jobkey = Jobkey.jobkey (Task.getjobname (), TAS K.getjobgroup ()); Scheduler.pausejob (Jobkey); } Restore a job public void Resumejob (Taskdo task) throws schedulerexception {Jobkey Jobkey = Jobkey.jobkey (Task.getjobname (), t Ask.getjobgroup ()); Scheduler.resumejob (Jobkey); Delete a job public void Deletejob (Taskdo task) throws schedulerexception {Jobkey Jobkey = Jobkey.jobkey (Task.getjobname (), t Ask.getjobgroup ()); Scheduler.deletejob (Jobkey); Immediately triggers the job public void Runjobnow (Taskdo task) throws schedulerexception {Jobkey Jobkey = Jobkey.jobkey (Task.getjobname (), t Ask.getjobgroup ()); Scheduler.triggerjob (Jobkey); Update Job expression copy code public void Updatejobcron (Taskdo task) throws schedulerexception {Triggerkey Triggerkey = Triggerkey.trigg ErKey (Task.getjobname (), Task.getjobgroup ()); Crontrigger trigger = (Crontrigger) scheDuler.gettrigger (Triggerkey); Cronschedulebuilder Schedulebuilder = Cronschedulebuilder.cronschedule (Task.getcronexpression ()); Trigger = Trigger.gettriggerbuilder (). withidentity (Triggerkey). Withschedule (Schedulebuilder). build (); Scheduler.reschedulejob (Triggerkey, Trigger); Copy Code easter egg part ~ Well, the body part basically on these, not much nonsense, this article does not have much to explain the principle, just simple application, the level is not enough also hope everybody forgive. See the above is not still a kind of see feel, Grandpa here also do a line of examples for everyone to experience ~ Interested students can personally test it.
Quartz Implementation of Java timed Apricot Platform Rental task dynamic configuration