Summary of java web timing task scheduling

Keywords: Java Tomcat xml SQL

When there is time, we need the server to silently perform scheduling tasks in the dead of night. Scheduling tasks based on java tomcat are done in two ways (personally):

1. Implementing the ServletContextListener class

1.SysContextListener class (configuration task timing scan)

 1 package com.srba.task;
 2 
 3 
 4 import java.util.Timer;//Timer class 
 5 
 6 import javax.servlet.ServletContextEvent;
 7 import javax.servlet.ServletContextListener; 
 8 public class SysContextListener implements ServletContextListener 
 9 { 
10   private Timer timer = null; 
11   //Rewrite contextInitialized 
12   public void contextInitialized(ServletContextEvent event) 
13   { 
14       //Initialize the listener here, in tomcat The timer function can be implemented here when the listener starts up. 
15       timer = new Timer(true); 
16       //To add logs, you can tomcat Viewed in the log 
17       event.getServletContext().log("Timer started"); 
18       System.out.println("+++++++++++++++++++++++++++The daily scheduling task of the system has been opened, and it is protecting the earth's security!++++++++++++++++++++++++++++");
19         int i=1000;       //1000 Milliseconds and 1 second
20         int s=1000*60*60; //Execute every 60 minutes (can be changed to 1000)*2,Scanning every 2 seconds)
21         Timer timer=new Timer();
22          //Call a timed task. i Represents that there is no delay in the task. s Represents every interval s The task is executed in milliseconds and the trigger interval is calculated in milliseconds. One second=1000 Millisecond.
23         timer.schedule(new TimerAction(event), i, s);
24       event.getServletContext().log("Tasks have been added"); 
25   } 
26   //Rewrite contextDestroyed 
27   public void contextDestroyed(ServletContextEvent event) 
28   { 
29       //Close the listener here, so destroy the timer here. 
30       timer.cancel(); 
31       event.getServletContext().log("Timer Destruction"); 
32   } 
33 } 

 

2.TimerAction class (specific tasks to be performed)

 1 package com.srba.task;
 2 
 3 
 4 import java.sql.SQLException;
 5 import java.text.DateFormat;
 6 import java.text.SimpleDateFormat;
 7 import java.util.Date;
 8 import java.util.TimerTask;
 9 
10 import javax.servlet.ServletContextEvent;
11 
12 import com.srba.web.AllUserInfoMaintenance; 
13 public class TimerAction extends TimerTask { 
14     private ServletContextEvent myevent;
15     TimerAction(ServletContextEvent event){
16         this.myevent = event;
17     }
18         public void run() {
19             SimpleDateFormat sdf=new SimpleDateFormat("HH");//Can be changed tonew SimpleDateFormat("ss"),Accurate to seconds
20             DateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
21             if(sdf.format(new Date()).equals("01")){// Every morning at 01:00 a.m.
22                 Date beginDate = new Date();
23                 myevent.getServletContext().log("Now["+myFormat.format(beginDate)+"]Start the synchronization task!");
24                 AllUserInfoMaintenance task = new AllUserInfoMaintenance();
25                 try {
26                     task.doUpdate();
27                     Date endDate = new Date();
28                     myevent.getServletContext().log("Now["+myFormat.format(endDate)+"]The execution of synchronization task is over!");
29                 } catch (SQLException e) {
30                     e.printStackTrace();
31                 }
32             }
33         }
34     
35 } 

3. Add the following contents to the <web-app> node in the web.xml of the project (note the path of the package):

  <listener> 
    <listener-class> 
        com.srba.task.SysContextListener 
    </listener-class> 
</listener> 

The first way is done happily.
Implementing the Application Listener <ContextRefreshedEvent> class

1.SrbaAutoTask class

 1 package com.srba.siss.rule.task;
 2 
 3 import java.text.SimpleDateFormat;
 4 import java.util.Date;
 5 import java.util.Timer;
 6 import java.util.TimerTask;
 7 
 8 import javax.annotation.Resource;
 9 
10 import org.springframework.context.ApplicationListener;
11 import org.springframework.context.event.ContextRefreshedEvent;
12 import org.springframework.stereotype.Service;
13 
14 import com.srba.siss.rule.service.SrbaRuleTaskService;
15 import com.srba.siss.rule.service.SystemCurrencyService;
16 
17 @Service
18 public class SrbaAutoTask implements ApplicationListener<ContextRefreshedEvent>
19 {    
20     @Resource
21     private SrbaRuleTaskService srbaRuleTaskService;
22     @Override
23     public void onApplicationEvent(ContextRefreshedEvent event) {
24         // TODO Auto-generated method stub
25         if(event.getApplicationContext().getParent() == null){
26             System.out.println("+++++++++++++++++++++++++++The daily scheduling task of the system has been opened, and it is protecting the earth's security!++++++++++++++++++++++++++++");
27             int i=1000;       //1000 Milliseconds and 1 second
28             int s=1000*60*60; //Execute every 60 minutes
29             Timer timer=new Timer();
30             timer.schedule(new TimerAction(event), i, s);
31         }
32     }
33 
34     
35 
36 
37 }

2.TimerAction() class, 2 of the same.

3. Configure the application Context. XML file and add the following (after tomcat starts spring loading, automatically execute the following classes)

<! - Auto-scan package com.srba.siss.rule.task, perform auto-execution task - > Auto-scan package com.srba.siss.rule.task
    <context:component-scan base-package="com.srba.siss.rule.task"></context:component-scan>

The second scheduling method is also happily configured.

The schedule() method in Timer has multiple overload formats to suit different situations. The format of the method is as follows:
 void schedule(TimerTask task, Date time)
Arrange to perform assigned tasks at specified times.
 void schedule(TimerTask task, Date firstTime, long period)
Arrange the specified tasks to start repetitive, fixed delays at the specified time.
 void schedule(TimerTask task, long delay)
Arrange to perform specified tasks after specified delays.
 void schedule(TimerTask task, long delay, long period)
Arrange for repetitive, fixed delays in execution of specified tasks starting after specified delays.
Timer is thread-safe and can be extended to a large number of simultaneous tasks (thousands of them are fine). All of its constructions start the timer thread. cancel() can be called to terminate the timer and discard all currently scheduled tasks. purge() removes all cancelled tasks from the timer's task queue. This class does not provide real-time assurance: it uses the Object.wait(long) method to schedule tasks.
TimerTask is an abstract class arranged by Timer for tasks that are executed once or repeatedly. It has an abstract method, run() -- the operation to be performed by the timer task. Therefore, each specific task class must inherit the TimerTask class and override the run() method. In addition, it has two non-abstract methods:
 boolean cancel()
Cancel this timer task.
 long scheduledExecutionTime()
Return the scheduled execution time for the most recent actual execution of this task.

Posted by LAMP on Fri, 07 Jun 2019 17:55:17 -0700