Spring Task Scheduler <task:scheduled-tasks> "Detailed description of cron parameters" (reproduced)

Source: Internet
Author: User
Tags aop

Within spring, a task is a set-time automatic task Scheduler that comes with spring.

Task is very convenient to use, but he can do less than quartz so much!

There are two ways to use annotations and configurations, which are configured in the following ways

Introduce spring at the beginning of Appcation.xml

<Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"XMLNS:AOP= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"Xmlns:context= "Http://www.springframework.org/schema/context"Xmlns:task= "Http://www.springframework.org/schema/task"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.          XSD HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop-4.0.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context-4.0.xsd Http://www.springframework.org/schema/task HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TASK/SPR Ing-task-4.0.xsd "Default-lazy-init= "true">  

<!--registering Beans--

<BeanID= "Voicefileclearjob"class= "Com.zjr.modules.boss.job.VoiceFileClearJob" />  <BeanID= "Versionlistenjob"class= "Com.zjr.modules.boss.job.VersionListenJob" />  <BeanID= "Statjob"class= "Com.zjr.modules.opstat.job.StatJob" />  

<!--start Task scheduling--

<Task:scheduled-tasks>      <task:scheduledref= "Voicefileclearjob"Method= "Execute"Initial-delay= "the"Fixed-delay= "3600000"/>      <task:scheduledref= "Versionlistenjob"Method= "Execute"Initial-delay= "the"Fixed-delay= "the"/>      <task:scheduledref= "Statjob"Method= "Statlgj"Cron= "0 * * *?"/>      <task:scheduledref= "Statjob"Method= "Statbadnameandqq"Cron= "* * * *?"/>  </Task:scheduled-tasks>  

The first task indicates that the program starts 5s and calls the Execute method in the Voicefileclearjob class, and then calls execute once every one hours

The third task represents a daily 23:59 call to the Statlgj method in the Statjob class

Ref is a work class

Method is the way to execute in a work class

Initial-delay is the delay before the task is called for the first time, unit milliseconds

Fixed-delay is the delay that is called again after the last call is completed

Fixed-rate is the delay that is called again after the start of the previous call (without waiting for the last call to complete)

Cron is an expression that indicates when a task is scheduled.

The following is the Versionlistenjob class code, the function is to monitor a folder, if there is any change in the contents of the folder to regenerate a TXT file, the file is recorded in the folder all the files related information.

 PackageCom.zjr.modules.boss.job; Import ...     Public classversionlistenjob {Logger Logger= Loggerfactory.getlogger (versionlistenjob.class); Private Static FinalString Gmboss_dir = "/data/jweb_static/jweb_wb_mgmt_beta/gmboss/"; Private Static FinalString gmboss_version_txt_file = "/data/jweb_static/jweb_wb_mgmt_beta/txt/version.txt"; Private Static FinalString Download_url = "http://beta.wbmgmt.youzijie.com/gmboss/"; Privatemap<string, string> versioninfomap =NewHashmap<>(); PrivateFile dir =NewFile (Gmboss_dir); PrivateFile Versiontxt =NewFile (Gmboss_version_txt_file);  PublicVersionlistenjob () {Try{init (); } Catch(IOException e) {logger.error ("Error occurs during Versionlistenjob", E); }      }        Private voidInit ()throwsIOException {if(!versiontxt.exists ()) versiontxt.createnewfile ();  for(String line:FileUtils.readLines (versiontxt)) {string[] array= Stringutils.split (line, "|")); if(Array.Length = = 5) versioninfomap.put (array[0], Array[4]); }      }         Public voidExecute ()throwsIOException {if(environmentutil.islocal () | |!dir.exists () | |!dir.isdirectory ()) {              return; }            //whether there is a file updateBoolean needupdate =false; List<File> Allfiles =GetFiles (Dir.getabsolutepath ());  for(File file:allfiles) {String FilePath=File.getpath (); LongLastmodifiedtime =file.lastmodified (); if(! Stringutils.equals (Lastmodifiedtime + "", Versioninfomap.get (FilePath))) {Needupdate=true;  Break; }          }            if(needupdate) {List<String> list =NewArraylist<>();  for(File file:allfiles) {List.add (File.getabsolutepath (). replace (Gmboss_dir,"/") + "|"                          + MD5 (file) + "|"                          + File.getpath (). Replace (Gmboss_dir,download_url) + "|"                          + file.length () + "|" +file.lastmodified ()); } fileutils.writelines (Versiontxt,"UTF-8", List, ioutils.line_separator_windows,false); Logger.info ("Versionlistenjob:gmboss has been updated"); }      }        //recursively get the list of all files in the directory     PublicList<file> getFiles (String filePath)throwsIOException {List<File> Allfiles =NewArraylist<>(); File Root=NewFile (FilePath); File files[]=Root.listfiles (); if(Files! =NULL&& Files.length! = 0) {               for(File file:files) {if(File.isdirectory ()) {Allfiles.addall (GetFiles (File.getabsolutepath ())); } Else{allfiles.add (file); }              }          }          returnAllfiles; }         PublicString MD5 (File f) {MessageDigest MD=NULL; Try{MD= Messagedigest.getinstance ("MD5"); } Catch(nosuchalgorithmexception ne) {ne.printstacktrace (); }          if(MD = =NULL)              return NULL; FileInputStream FIS=NULL; Try{FIS=NewFileInputStream (f); byte[] buffer =New byte[8192]; intlength;  while(length = fis.read (buffer))! =-1) {md.update (buffer,0, length); }              return NewString (Hex.encodehex (Md.digest ())). toUpperCase (); } Catch(Exception e) {logger.error ("Error occurs during MD5 file", E); return NULL; } finally {              Try {                  if(FIS! =NULL) Fis.close (); } Catch(IOException e) {logger.error ("Error occurs during MD5 file", E); }          }      }  }  

Cron expression:

A cron expression has at least 6 (or possibly 7) time elements that have a space separation.
In order of
Seconds (0~59)
Minutes (0~59)
Hours (0~23)
Days (months) (0~31, but you need to consider the number of days of your month)
Month (0~11)
Days (weeks) (1~7 1=sun or Sun,mon,tue,wed,thu,fri,sat)
Year (1970-2099)


Each of these elements can be a value (such as 6), a continuous interval (9-12), a time interval (8-18/4) (/= every 4 hours), a list (1,3,5), and a wildcard character. Because the "date in the month" and "date in the week" are mutually exclusive, one of the two elements must be set.

0 0 10,14,16 * *? 10 o'clock in the morning, 2 o'clock in the afternoon, 4 O ' Day
0 0/30 9-17 * *? Every half hour for nine to five working hours
0 0 12? * WED means every Wednesday noon 12 o'clock
"0 0 12 * *?" trigger 12 o'clock noon every day.
"0 15 10?" * * "trigger 10:15 every day"
"0 15 10 * *?" Daily 10:15 Trigger
"0 15 10 * *?" * "10:15 per day" trigger
"0 15 10 * *?" 2005 "2005-year daily 10:15 Trigger
"0 * 14 * *?" triggers every 1 minutes from 2 o'clock in the afternoon to 2:59 daily
"0 0/5 14 * *?" triggers every 5 minutes from 2 o'clock in the afternoon to 2:55 daily
"0 0/5 14,18 * *?" triggers every 5 minutes from 2 o'clock in the afternoon to 2:55 daily and from 6 o'clock in the afternoon to 6:55
"0 0-5 14 * *?" triggers every 1 minutes from 2 o'clock in the afternoon to 2:05 daily
"0 10,44 14?" 3 WED "2:10 and 2:44 triggers in Wednesday of every March
"0 15 10?" * Mon-fri "Monday to Friday 10:15 trigger
"0 15 10 15 *?" 15th 10:15 per month
"0 L *?" 10:15 on the last day of the month
"0 15 10?" * 6L "Last month of Friday 10:15 Trigger
"0 15 10?" * 6L 2002-2005 "2002 to 2005 the last of the monthly Friday 10:15 trigger
"0 15 10?" * 6#3 "Monthly third Friday 10:15 trigger

Some sub-expressions can contain ranges or lists

For example: subexpression (Day (week)) can be "Mon-fri", "Mon,wed,fri", "Mon-wed,sat"

The "*" character represents all possible values

Therefore, "*" in the sub-expression (month) represents the meaning of each month, "*" in the subexpression (Day (week)) represents every day of the week
The "/" character is used to specify the increment of the numeric value

For example: "0/15" in sub-expressions (minutes) means starting from the No. 0 minute, every 15 minutes

"3/20" in the sub-expression (minutes) means that every 20 minutes (it is the same as "3,23,43") starting from the 3rd minute

“? "Character is used only for days (months) and days (weeks) of two sub-expressions, indicating that no value is specified

When one of the 2 sub-expressions is assigned a value, in order to avoid a conflict, you need to set the value of another subexpression to "? ”

The "L" character is used only for days (months) and days (weeks) of two sub-expressions, which is the abbreviation for the word "last"


But it has a different meaning in two sub-expressions.


In the day (month) subexpression, "L" represents the last day of the one-month


In the day (week) Self-expression, "L" represents the last day of one weeks, the SAT


If there is something specific before "L", it has other meanings.


For example: "6L" means the 6th day of the month, and "Fril" means the last Friday of the month.


Note: When using the "L" parameter, do not specify a list or range, as this can cause problems

allowed
Field special characters for allowable values

Seconds

0-59

, - * /

Score of

0-59

, - * /

Hours

0-23

, - * /

Date

1-31

, - * ? /L W C

Month

1-12 or Jan-dec

, - * /

Week

1-7 or Sun-sat

, - * ? /L C #

Year (optional)

Leave Blank, 1970-2099

, - * /

Spring Task Scheduler <task:scheduled-tasks> "Detailed description of cron parameters" (reproduced)

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.