[BAT] [JAVA] Timing task-quartz using the article __java

Source: Internet
Author: User
Tags documentation

-quartz of timed tasks

Quartz is a opensymphony open source organization in the Job scheduling field another open source project, it can be combined with Java EE and J2SE applications can also be used alone. Quartz can be used to create simple or complex day programs for running 10, hundred, and even tens of thousands of jobs. Jobs can be made into standard Java components or EJBs. Official website: Http://www.opensymphony.com/quartz

Related jars:
Quartz-all-1.6.0.jar
Jta.jar
Commons-logging-1.1.jar
Commons-collections3.2.jar

Encapsulated Management classes:

/** * Copyright: Huaxin Software * Project name: Public module * Creator: WANGDF * Date Created: 2011-1-22 * File Description: Scheduled Task management category * Recently modified by: WANGDF * Last modified: 2011-1-22/Package C Om.extjweb.quartz; Import java.text.ParseException; Import Org.quartz.CronTrigger; Import Org.quartz.JobDetail; Import Org.quartz.Scheduler; Import org.quartz.SchedulerException; Import Org.quartz.SchedulerFactory; Import Org.quartz.impl.StdSchedulerFactory; /** * Timer Task Management class * * @author Wang Seal/public class Quartzmanager {private static schedulerfactory gschedulerfactory = new StdS Chedulerfactory (); private static String Job_group_name = "Extjweb_jobgroup_name"; private static String Trigger_group_name = "Extjweb_triggergroup_name"; /** * Add a timed task, using the default task group name, trigger name, trigger Group name * * @param jobName * Task Name * @param jobclass * task * @param time setting, reference quartz documentation * @t Hrows schedulerexception * @throws parseexception * * public static void AddJob (String jobName, String Jobclass, String Tim E) {try {Scheduler sched = Gschedulerfactory.getscheduler (); Jobdetail jobdetail = new Jobdetail(JobName, Job_group_name, Class.forName (Jobclass))//Task Name, Task Group, Task execution class//trigger Crontrigger Trigger = new Crontrigger (jobName , trigger_group_name),//Trigger name, trigger group Trigger.setcronexpression (time),//Trigger timing Sched.schedulejob (Jobdetail, TRIGGER); Start if (!sched.isshutdown ()) {Sched.start ();}} catch (Exception e) {e.printstacktrace (); throw new RuntimeException (e);}} /** * Add a timed task * * @param jobName * Task Name * @param jobgroupname * Task Group name * @param triggername * Trigger name * @param triggergroupname * Trigger Group Name * @param jobclass * task * @param time setting, refer to Quartz documentation * @throws schedulerexception * @throws parseexception * * public static void AddJob (String jobName, String jobgroupname, String triggername, String triggergroupname, String Jobcla SS, String time) {try {Scheduler sched = Gschedulerfactory.getscheduler (); Jobdetail jobdetail = new Jobdetail (JobName, Jobgroupname, Class.forName (Jobclass))//Task Name, Task Group, Task execution class//trigger Crontrigger T rigger = new Crontrigger (triggername, triggergroupname);//trigger Name, trigger group TRIgger.setcronexpression (time);//Trigger Timing set Sched.schedulejob (Jobdetail, Trigger); catch (Exception e) {e.printstacktrace (); throw new RuntimeException (e);}} /** * Modify the trigger time for a task (using default task group name, trigger name, trigger group name) * * @param jobName * @param time/public static void Modifyjobtime (String Jobnam E, String Time {try {Scheduler sched = Gschedulerfactory.getscheduler (); Crontrigger trigger = (Crontrigger) sched.gettrigger (JobName, trigger_group_name); if (trigger = = null) {return;} String oldtime = Trigger.getcronexpression (); if (!oldtime.equalsignorecase (time)) {Jobdetail Jobdetail = Sched.getjobdetail (JobName, job_group_name); Class Objjobclass = Jobdetail.getjobclass (); String Jobclass = Objjobclass.getname (); Removejob (JobName); AddJob (JobName, Jobclass, time); The catch (Exception e) {e.printstacktrace (); throw new RuntimeException (e);}} /** * Modify the trigger time of a task * * @param triggername * @param triggergroupname * @param time/public static void Modifyjobtime (Strin G Triggername, String TriggergroUpname, String time) {try {Scheduler sched = Gschedulerfactory.getscheduler (); Crontrigger trigger = (Crontrigger) sched.gettrigger (triggername, triggergroupname); if (trigger = = null) {return;} String oldtime = Trigger.getcronexpression (); if (!oldtime.equalsignorecase (time)) {Crontrigger ct = (Crontrigger) trigger;//////////////////REBOOT Trigger Device Sched.resumetrigger (triggername, triggergroupname); The catch (Exception e) {e.printstacktrace (); throw new RuntimeException (e);}} /** * Remove a task (using default task group name, trigger name, trigger group name) * * @param jobName */public static void Removejob (String jobName) {try {Scheduler SC hed = Gschedulerfactory.getscheduler (); Sched.pausetrigger (JobName, trigger_group_name);/Stop Trigger Sched.unschedulejob (JobName, trigger_group_name);//Remove Trigger Sched.deletejob (JobName, job_group_name);//Delete task} catch (Exception e) {e.printstacktrace (); throw new RuntimeException ( e); }/** * Remove a task * * @param jobName * @param jobgroupname * @param triggername * @param TriggergRoupname */public static void Removejob (String jobName, String jobgroupname, String triggername, String triggergroupname) {try {Scheduler sched = Gschedulerfactory.getscheduler (); Sched.pausetrigger (Triggername, triggergroupname);/Stop Trigger S Ched.unschedulejob (Triggername, triggergroupname);//Remove triggers sched.deletejob (jobName, jobgroupname);//delete tasks} catch ( Exception e) {e.printstacktrace (); throw new RuntimeException (e);}} /** * Start all timed tasks */public static void Startjobs () {try {Scheduler sched = Gschedulerfactory.getscheduler (); Sched.start () ; catch (Exception e) {e.printstacktrace (); throw new RuntimeException (e);}} /** * Close all Scheduled Tasks/public static void Shutdownjobs () {try {Scheduler sched = Gschedulerfactory.getscheduler (); if (!sched. IsShutDown ()) {Sched.shutdown ();}} catch (Exception e) {e.printstacktrace (); throw new RuntimeException (e);}} }

Transform the 202 line code of the Quartz Jobrunshell class to enable the scheduled task to support the full transaction of the database and the shutdown of the database connection:

Execute the job try {log.debug ("Calling Execute on Job" + jobdetail.getfullname ()); Job.execute (JEC); 2011/1/22 Wang Seal added dbutil.commit (); Endtime = System.currenttimemillis (); catch (Jobexecutionexception jee) {endtime = System.currenttimemillis (); jobexex = jee;//2011/1/22 Wang Seal add dbutil.roll Back (); GetLog (). info ("Job" + jobdetail.getfullname () + "threw a jobexecutionexception:", Jobexex);} catch (Throwable e) {endtime = System.currenttimemillis (); GetLog (). Error ("Job" + jobdetail.getfullname () + "threw an U nhandled Exception: ", e); Schedulerexception se = new Schedulerexception ("Job threw an unhandled exception.", E); Se.seterrorcode (schedulerexception.err_job_execution_threw_exception); Qs.notifyschedulerlistenerserror ("Job" + jec.getjobdetail (). Getfullname () + "threw an exception.", SE); Jobexex = new Jobexecutionexception (SE, false); Jobexex.seterrorcode (jobexecutionexception.err_job_execution_threw_exception); 2011/1/22 Wang Seal added dbutil.rollback (); } finallY {//2011/1/22 Wang Seal Add dbutil.closecurrentconnection ();}

Test code:

SYSTEM.OUT.PRINTLN ("System startup" starts (output once every 1 seconds) ... "); Quartzmanager.addjob (job_name, Job, "0/1 * * * *"); Quartzmanager.addjob (job_name, Job, "0 0/3 8-20"?) *"); Thread.Sleep (5000); System.out.println ("Modify Time" start (output once every 2 seconds) ... "); Quartzmanager.modifyjobtime (job_name, "10/2 * * * *"); Thread.Sleep (6000); System.out.println ("Remove timed" start ...); Quartzmanager.removejob (job_name); System.out.println ("Remove timed" success); SYSTEM.OUT.PRINTLN ("/n" Add timed Task Again "start (output once every 10 seconds) ..."); Quartzmanager.addjob (job_name, Job, "*/10 * * *"); Thread.Sleep (60000); System.out.println ("Remove timed" start ...); Quartzmanager.removejob (job_name); System.out.println ("Remove timed" success);Package Com.extjweb.quartz Import Java.util.Calendar import org.quartz.Job Import Org.quartz.JobExecutionContext; Import org.quartz.JobExecutionException; The public class Testjob implements Job {@SuppressWarnings ("deprecation") is public void execute (jobexecutioncontext arg0) thro WS jobexecutionexception {System.out.println (Calendar.getinstance (). GetTime (). toLocaleString () + "★★★★★★★★★★★");} Quartz Time Configuration rules

Format: [SEC] [minutes] [hours] [day] [month] [week] [year]

Serial number Description
is required Values that are allowed to be filled in Wildcard characters allowed
1 Seconds Is 0-59 , - * /
2 Part Is 0-59
, - * /
3 Hours Is 0-23 , - * /
4 Day Is 1-31 , - * ? /L W
5 Month Is 1-12 or Jan-dec , - * /
6 Week Is 1-7 or Sun-sat , - * ? L
7 Years Whether Empty or 1970-2099 , - * /

Wildcard Description:
*Represents all values. For example, setting "*" on a divided field means that every minute is triggered.
?Indicates that no value is specified. The scenario used is a value that does not need to be concerned about the current setting of this field. For example: to trigger an operation at number 10th per month, but don't care what the week is, so the field needs to be set to "?" set to 0 0 0 10 *?
-Represents an interval. For example, set "10-12" on the hour, indicating that the 10,11,12 point will be triggered.
,Indicates that multiple values are specified, such as setting "Mon,wed,fri" on the week field to indicate Monday, Wednesday, and Friday triggers
/Used to increment the trigger. If you set "5/15" above the second to indicate starting from 5 seconds, each 15 second trigger (5,20,35,50). Set the ' 1/3 ' on the month field to start with the 1th number per month, triggering once every three days.
LTo express the last meaning. On the day field setting, the last day of the month (according to the current month, if the February will also be based on whether the run year [leap]), in the weekly field of Saturday, the equivalent of "7" or "SAT." If you add a number before "L", it represents the last of the data. For example, a format such as "6L" is set on the week field, which means "last Friday of this month"
WRepresents the most recent working day from the specified date (Monday to Friday). For example, set "15W" on the day field to indicate the most recent weekday from 15th per month. If number 15th is exactly Saturday, find the most recent Friday (14th) trigger, and if 15th is weeks, find the nearest next Monday (16th) trigger. If the 15th number is exactly on the weekday (Monday to Friday), it is triggered on that day. If the specified format is "1W", it represents the most recent weekday trigger after the 1th number per month. If number 1th is Saturday, it will be triggered under number 3rd in Monday. (Note, "W" can only set a specific number, do not allow interval "-").
Small Tips

' L ' and ' W ' can be used in a combination. If "LW" is set on the day field, it will be triggered on the last weekday of this month (generally refers to payroll)

#Ordinal number (the number of weeks of the month), such as setting "6#3" on the week field for the third Saturday of the month. Note If you specify "#5" and the fifth week is not Saturday, the configuration is not triggered (used on Mother's Day and Father's Day).
Small Tips

The setting of the week field, if the English alphabet is case-insensitive, the MON is the same as the MON.



Common examples:

0 0 12 * *? Triggered at 12 a day.
0 15 10? * * Triggers 10:15 every day.
0 15 10 * *? Triggers 10:15 every day.
0 15 10 * *? * Triggers 10:15 every day.
0 15 10 * *? 2005 2005 Daily 10:15 Trigger
0 * 14 * *? Every afternoon at 2 O ' 2:59, each minute triggers
0 0/5 14 * *? Every afternoon at 2 O ' 2:59 (the whole point starts, every 5 minutes triggers)

0 0/5 14,18 * *?

Every afternoon at 2 O ' 2:59 (the whole point starts, every 5 minutes triggers)
Every afternoon at 18 O ' 18:59 (the whole point starts, every 5 minutes triggers)
0 0-5 14 * *? Every afternoon at 2 O ' 2:05, each minute triggers
0 10,44 14? 3 WED March every Wednesday afternoon 2:10 and 2:44 triggering
0 15 10? * Mon-fri From Monday to Friday every morning of 10:15 triggers
0 15 10 15 *? 15th per month, 10:15 A.M. trigger.
0 L *? 10:15 trigger on the last day of the month
0 15 10? * 6L The last week of the month of Friday 10:15 Trigger
0 15 10? * 6L 2002-2005 From 2002 to 2005 the last week of the month of Friday 10:15 triggered
0 15 10? * 6#3 The third week of the month of Friday starts to trigger
0 0 12 1/5 *? The first noon of the month starts every 5 days.
0 11 11 11 11? Every November 11 11:11 trigger (Singles Day)

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.