Add a method for timing tasks to the Java Web project

  • 2021-01-03 20:52:55
  • OfStack

There are two ways to add timed tasks to the Java Web program: 1. Use listener injection; 2. Use the Spring annotation @Scheduled injection.

The second form is recommended.

1. Use listener injection

: Create listener class:


import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class TimerDataTaskListener implements ServletContextListener {
 
 @Override
 public void contextInitialized(ServletContextEvent servletContextEvent) {
  new TimerManager();
 }
 
 @Override
 public void contextDestroyed(ServletContextEvent servletContextEvent) {

 }
}

: Create a timed task class:


import java.util.Calendar;
import java.util.Date;
import java.util.Timer;

public class TimerManager {
 // The time interval :24h
 private static final long PERIOD_DAY = 24 * 60 * 60 * 1000;
 public TimerManager() {
  Calendar calendar = Calendar.getInstance();

  // Custom daily 12:30:30 perform 
  calendar.set(Calendar.HOUR_OF_DAY, 12);
  calendar.set(Calendar.MINUTE, 30);
  calendar.set(Calendar.SECOND, 30);

  Date date = calendar.getTime();  // The first 1 The time it takes to perform a scheduled task 
  // If the current time has elapsed since the time point, then in 2 The execution starts at the time of day 
  if (date.before(new Date())) {
   date = this.addDay(date, 1);
  }
  Timer timer = new Timer();
  TimerTaskService task = new TimerTaskService();
  // Schedule the specified task to begin repeated fixed delay execution at the specified time. 
  timer.schedule(task, date, PERIOD_DAY);
 }

 //  Add or subtract days 
 private Date addDay(Date date, int num) {
  Calendar startDT = Calendar.getInstance();
  startDT.setTime(date);
  startDT.add(Calendar.DAY_OF_MONTH, num);
  return startDT.getTime();
 }
}

: Create TimerTask class:


import java.util.TimerTask;

public class TimerTaskService extends TimerTask {

 @Override
 public void run() {
  try {
   // The logic of the task to be performed is written here 
   System.out.println(" Password inserted successfully! ");
  } catch (Exception e) {
   System.out.println(" Password insertion failed! ");
  }
 }
}

: Register the listener in ES21en.xml


<!-- TimerDataTaskListener  The listener  -->
 <listener>
  <listener-class>com.jsiqi.resume.service.TimerDataTaskListener</listener-class>
 </listener> 

2. Use spring annotation injection

The framework of my project is Spring + SpringMVC + Mybatis

Code examples:


import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class TimerTask {
 
 @Scheduled(cron="*/30 * * * * *") //  interval 30 Seconds to perform 
 public void test(){
  try {
   // The logic of the task to be performed is written here 
   System.out.println(" Password inserted successfully! ");
  } catch (Exception e) {
   System.out.println(" Password insertion failed! ");
  }
 }
}

The setting method of timing time is as follows:


CronTrigger The complete configuration format is:  [ seconds ] [ points ] [ hours ] [ day ] [ month ] [ weeks ] [ years ]
 Example: 
0 0 10,14,16 * * ?  Every morning 10 Points, in the afternoon 2 Points, 4 point 
0 0/30 9-17 * * ?  the 9 On the evening of 5 Every half hour during working hours 
0 0 12 ? * WED  Every week 3 At noon, 12 point  
"0 0 12 * * ?"  Every day at noon 12 Some trigger  
"0 15 10 ? * *"  Every morning 10:15 The trigger  
"0 15 10 * * ?"  Every morning 10:15 The trigger  
"0 15 10 * * ? *"  Every morning 10:15 The trigger  
"0 15 10 * * ? 2005" 2005 Every morning in 1977 10:15 The trigger  
"0 * 14 * * ?"  Every afternoon 2 Point to the afternoon 2:59 During each of the 1 Minutes to trigger  
"0 0/5 14 * * ?"  Every afternoon 2 Point to the afternoon 2:55 During each of the 5 Minutes to trigger  
"0 0/5 14,18 * * ?"  Every afternoon 2 Point to the 2:55 Period and afternoon 6 Point to the 6:55 During each of the 5 Minutes to trigger  
"0 0-5 14 * * ?"  Every afternoon 2 Point to the afternoon 2:05 During each of the 1 Minutes to trigger  
"0 10,44 14 ? 3 WED"  Every year, 3 On the week 3 In the afternoon 2:10 and 2:44 The trigger  
"0 15 10 ? * MON-FRI"  weeks 1 To a week 5 In the morning 10:15 The trigger  
"0 15 10 15 * ?"  A month 15 The morning of 10:15 The trigger  
"0 15 10 L * ?"  Finally a month 1 Day morning 10:15 The trigger  
"0 15 10 ? * 6L"  End of the month 1 A few weeks 5 In the morning 10:15 The trigger  
"0 15 10 ? * 6L 2002-2005" 2002 - 2005 At the end of each month of the year 1 A few weeks 5 In the morning 10:15 The trigger  
"0 15 10 ? * 6#3"  Every month of the first 3 A few weeks 5 In the morning 10:15 The trigger  

序号 说明 是否必填 允许填写的值 允许的通配符
1 0-59 , - * /
2 0-59 , - * /
3 0-23 , - * /
4 1-31 , - * ? / L W
5 1-12或JAN-DEC , - * /
6 1-7或SUN-SAT , - * ? / L W
7 empty 或1970-2099 , - * /

Wildcard description:

* represents all values. For example, setting "*" on a sub field means that it will fire every 1 minute

The & # 63; Indicates that no value is specified. The scenario used does not need to care about the current setting value of this field.

For example: To trigger an operation on the 10th of each month, regardless of the day of the week, so the field that needs the week position is set to "?" Specific setting is 0 0 0 10 * ?

Minus is the interval. For example, setting "10-12" on hours means that 10,11, and 12 will trigger.

To specify multiple values, such as setting "MON,WED,FRI" on the week field to trigger week 1, week 3, and week 5

/ Used for incremental triggering. Setting "5/15" on seconds means starting from 5 seconds and firing every 15 seconds (5,20,35,50). Set '1/3' on the month field to start on the 1st of each month and trigger once every 3 days.

L means the final meaning. On the day field setting, means the last day of the month (depending on the current month, or if it's February, depending on whether it's run year [leap]), and on the week field, means Week 6, equivalent to "7" or "SAT." If a number is appended to "L", it is the last digit of the data. For example, setting "6L" on the week field means "The last Friday of the month"

W represents the most recent working day (week 1 to Week 5) from the specified date. For example, set "15W" on the day field to indicate the working day closest to the 15th of each month. If the 15th happens to be The 6th week, find the latest 5th (14th) to trigger. If the 15th is the end of the week, find the latest next Monday (16th) to trigger. If the 15th falls on a business day (week 1 to Week 5), it will trigger on that day. If the format is specified as "1W", it is triggered on the most recent business day after the 1st of each month. If the 1st is Week 6, it will trigger on the 3rd and next Monday. (Note, only specific numbers can be set before "W", and no interval "-" is allowed).

For example, set "6#3" on the week field to indicate that it is on week 6 of the third week of the month. Note that if you specify "#5" and there is no week 6 in week 5, this configuration will not be triggered (perfect for Mother's Day and Father's Day);

Tip:
'L' and 'W' can be used in combination. If "LW" is set on the day field, it is triggered on the last business day of the month;
Setting of week field, if using English letters is case-insensitive, MON is the same as mon;

Reference:

https://www.cnblogs.com/liaojie970/p/5913272.html

http://prisonbreak.iteye.com/blog/2247216


Related articles: