Spring Task Scheduling <task:scheduled-tasks> [Detailed with cron parameters]

Keywords: Attribute Spring xml less

There is a task in Spring, which is a set-time automatic task scheduling that Spring brings with it.

task is easy to use, but it can do less than quartz!

You can use annotations and configuration in the following ways


Introduce Spring at the beginning of appcation.xml

  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xmlns:aop="http://www.springframework.org/schema/aop"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:task="http://www.springframework.org/schema/task"  
  6.     xsi:schemaLocation="  
  7.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
  8.         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
  9.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd  
  10.         http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd"  
  11.     default-lazy-init="true">  

Registered bean s
  1. <bean id="voiceFileClearJob" class="com.zjr.modules.boss.job.VoiceFileClearJob" />  
  2. <bean id="versionListenJob" class="com.zjr.modules.boss.job.VersionListenJob" />  
  3. <bean id="statJob" class="com.zjr.modules.opstat.job.StatJob" />  

<! - - - Open Task Scheduling - > Open Task Scheduling

  1. <task:scheduled-tasks>  
  2.     <task:scheduled ref="voiceFileClearJob" method="execute" initial-delay="5000" fixed-delay="3600000"/>  
  3.     <task:scheduled ref="versionListenJob" method="execute" initial-delay="5000" fixed-delay="5000"/>  
  4.     <task:scheduled ref="statJob" method="statLgj" cron="0 59 23 * * ?"/>  
  5.     <task:scheduled ref="statJob" method="statBadNameAndQQ" cron="23 28 20 * * ?"/>  
  6. </task:scheduled-tasks>  

The first task represents calling the execute method in the voiceFileClearJob class five seconds after the program starts, and then calling execute again every hour.

The third task represents a daily call to the statLgj method in the statJob class at 23:59


ref is a working class

Method is the method to be executed in the working class

initial-delay is the delay in milliseconds before the task is first invoked.

fixed-delay is the delay of calling again after the last call is completed

fixed-rate is the delay of calling again after the last call starts (without waiting for the last call to complete)

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


Following is the code of the versionListenJob class mentioned above. The function is to monitor a folder. If there are any changes in the contents of the folder, a txt file will be regenerated. The file records the relevant information of all the files in the folder.

  1. package com.zjr.modules.boss.job;  
  2.   
  3. import ...  
  4.   
  5. public class VersionListenJob {  
  6.   
  7.     Logger logger = LoggerFactory.getLogger(VersionListenJob.class);  
  8.   
  9.     private static final String GMBOSS_DIR = "/data/jweb_static/jweb_wb_mgmt_beta/gmboss/";  
  10.     private static final String GMBOSS_VERSION_TXT_FILE = "/data/jweb_static/jweb_wb_mgmt_beta/txt/version.txt";  
  11.     private static final String DOWNLOAD_URL = "http://beta.wbmgmt.youzijie.com/gmboss/";  
  12.   
  13.     private Map<String, String> versionInfoMap = new HashMap<>();  
  14.     private File dir = new File(GMBOSS_DIR);  
  15.     private File versionTxt = new File(GMBOSS_VERSION_TXT_FILE);  
  16.   
  17.     public VersionListenJob() {  
  18.         try {  
  19.             init();  
  20.         } catch (IOException e) {  
  21.             logger.error("error occurs during VersionListenJob", e);  
  22.         }  
  23.     }  
  24.   
  25.     private void init() throws IOException {  
  26.   
  27.         if (!versionTxt.exists())  
  28.             versionTxt.createNewFile();  
  29.   
  30.         for (String line : FileUtils.readLines(versionTxt)) {  
  31.             String[] array = StringUtils.split(line, "|");  
  32.             if (array.length == 5)  
  33.                 versionInfoMap.put(array[0], array[4]);  
  34.         }  
  35.     }  
  36.   
  37.     public void execute() throws IOException {  
  38.   
  39.         if (EnvironmentUtil.isLocal() || !dir.exists() || !dir.isDirectory()) {  
  40.             return;  
  41.         }  
  42.   
  43.         //Is there a file update?  
  44.         Boolean needUpdate = false;  
  45.         List<File> allFiles = getFiles(dir.getAbsolutePath());  
  46.   
  47.         for (File file : allFiles) {  
  48.             String filePath = file.getPath();  
  49.             long lastModifiedTime = file.lastModified();  
  50.             if (!StringUtils.equals(lastModifiedTime + "", versionInfoMap.get(filePath))) {  
  51.                 needUpdate = true;  
  52.                 break;  
  53.             }  
  54.         }  
  55.   
  56.         if (needUpdate) {  
  57.             List<String> list = new ArrayList<>();  
  58.             for (File file : allFiles) {  
  59.                 list.add(file.getAbsolutePath().replace(GMBOSS_DIR,"/") + "|"  
  60.                         + md5(file) + "|"  
  61.                         + file.getPath().replace(GMBOSS_DIR,DOWNLOAD_URL) + "|"  
  62.                         + file.length() + "|"  
  63.                         + file.lastModified());  
  64.             }  
  65.             FileUtils.writeLines(versionTxt,"UTF-8", list, IOUtils.LINE_SEPARATOR_WINDOWS,false);  
  66.             logger.info("VersionListenJob: Gmboss has been updated");  
  67.         }  
  68.     }  
  69.   
  70.     //Recursively retrieves a list of all files in a directory  
  71.     public List<File> getFiles(String filePath) throws IOException {  
  72.   
  73.         List<File> allFiles = new ArrayList<>();  
  74.   
  75.         File root = new File(filePath);  
  76.         File files[] = root.listFiles();  
  77.         if (files != null && files.length != 0) {  
  78.             for (File file : files) {  
  79.                 if (file.isDirectory()) {  
  80.                     allFiles.addAll(getFiles(file.getAbsolutePath()));  
  81.                 } else {  
  82.                     allFiles.add(file);  
  83.                 }  
  84.             }  
  85.         }  
  86.         return allFiles;  
  87.     }  
  88.   
  89.     public String md5(File f) {  
  90.         MessageDigest md = null;  
  91.         try {  
  92.             md = MessageDigest.getInstance("MD5");  
  93.         } catch (NoSuchAlgorithmException ne) {  
  94.             ne.printStackTrace();  
  95.         }  
  96.         if (md == null)  
  97.             return null;  
  98.         FileInputStream fis = null;  
  99.         try {  
  100.             fis = new FileInputStream(f);  
  101.             byte[] buffer = new byte[8192];  
  102.             int length;  
  103.             while ((length = fis.read(buffer)) != -1) {  
  104.                 md.update(buffer, 0, length);  
  105.             }  
  106.             return new String(Hex.encodeHex(md.digest())).toUpperCase();  
  107.         } catch (Exception e) {  
  108.             logger.error("error occurs during md5 file", e);  
  109.             return null;  
  110.         } finally {  
  111.             try {  
  112.                 if (fis != null)  
  113.                     fis.close();  
  114.             } catch (IOException e) {  
  115.                 logger.error("error occurs during md5 file", e);  
  116.             }  
  117.         }  
  118.     }  
  119. }  


The cron expression:

A cron expression has at least six (or possibly seven) space-separated time elements.
In order of order, the following is the order of uuuuuuuuuuu
Second (0-59)
Minutes (0-59)
Hours (0-23)
Days (months) (0-31, but you need to consider the number of days in your month)
Month (0-11)
Day (week) (1-7 1 = SUN or SUN, MON, TUE, WED, THU, FRI, SAT)
Year (1970-2099)


Each element can be a value (e.g. 6), a continuous interval (9-12), an interval (8-18/4) (/ representing every four hours), a list (1, 3, 5), wildcards. Because "Date in Month" and "Date in Week" are mutually exclusive, one of them must be set?

00 10, 14, 16*? Every day at 10 a.m., 2 p.m., 4 p.m.
0/309-17*? Every half hour during the nine-to-five working hours
0012?* WED means 12 noon every Wednesday.
"0 02 * *?" Triggered at 12 noon every day.
"0 1510?*" is triggered at 10:15 a.m. every day.
"0 1510 * *?" Triggered at 10:15 a.m. every day.
"0 1510 *?*" is triggered at 10:15 a.m. every day.
"0 1510 *? 2005" triggered at 10:15 a.m. in 2005
"0 * 14 *?" Triggered every minute from 2 p.m. to 2 p.m. at 2:59 p.m.
"0/514* *?" Triggered every five minutes between 2 p.m. and 2:55 p.m. every day.
"0/514, 18* *?" Triggered every five minutes between 2 p.m. and 2:55 p.m. and between 6 p.m. and 6:55 p.m.
"0-5 14* *?" Triggered every minute between 2 p.m. and 2 p.m. every day.
"0 10,44 14?3 WED" is triggered at 2:10 and 2:44 p.m. on Wednesday, March each year.
"0 1510?* MON-FRI" triggers from 10:15 a.m. Monday to Friday.
"0 15 10 15 *?" Triggered at 10:15 a.m. on the 15th of each month.
"0 1510 L*?" Triggered at 10:15 a.m. on the last day of each month.
"0 1510?* 6L" is triggered at 10:15 a.m. on the last Friday of each month.
"0 1510?* 6L 2002-2005" triggered at 10:15 a.m. on the last Friday of each month from 2002 to 2005
Triggered at 10:15 a.m. on the third Friday of the month

Some subexpressions can contain ranges or lists

For example, sub-expressions (days (weeks) can be "MON-FRI", "MON, WED, FRI", "MON-WED,SAT".

The "*" character represents all possible values

Therefore, "*" means every month in the sub-expression (month), and "*" means every day of the week in the sub-expression (day (week).
The "/" character is used to specify the increment of the value

For example, "0/15" in a subexpression (minute) means that it starts at minute 0, every 15 minutes.

"3/20" in a subexpression (minute) means every 20 minutes (it has the same meaning as "3, 23, 43") starting at the third minute.

"?" Characters are used only for day (month) and day (week) sub-expressions, indicating no specified value.

When one of the two sub-expressions has been assigned a value, in order to avoid conflict, the value of the other sub-expression needs to be set to "?"

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


But it has different meanings in two sub-expressions.


In the sky (month) subexpression, "L" means the last day of a month.


In the day (week) self-expression, "L" means the last day of a week, that is, SAT.


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


For example, "6L" means the penultimate sixth 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.

 

field   Allowable value   Allowed special characters

Second
 
0-59 
 
, - * / 

Points
 
0-59 
 
, - * / 

Hour
 
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 empty, 1970-2099
 
, - * / 



Posted by loopykd on Thu, 03 Jan 2019 16:06:10 -0800