Summary of java web timed task scheduling

Sometimes we need the server to silently perform scheduling tasks in the dead of night. The scheduling tasks based on java tomcat are in the following two ways (practice personally):

1. Implement the ServletContextListener class

1. SysContextListener class (configure task timing scan)

 
 1 package com.srba.task;
 2 
 3 
 4 import java.util.Timer;//定时器类 
 5 
 6 import javax.servlet.ServletContextEvent;
 7 import javax.servlet.ServletContextListener; 
 8 public class SysContextListener implements ServletContextListener 
 9 { 
10   private Timer timer = null; 
11   //重写contextInitialized 
12   public void contextInitialized(ServletContextEvent event) 
13   { 
14        // Initialize the listener here, the listener starts when tomcat starts, and the timer function can be implemented here 
15        timer = new Timer( true ); 
 16        // Add log, you can view 
17        event in the tomcat log. getServletContext().log("Timer started" ); 
 18        System.out.println("++++++++++++++++++++++++++++System The daily scheduling task has been opened, and the earth is being protected! ++++++++++++++++++++++++++++" );
 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, scan every 2 seconds) 
21          Timer timer= new Timer();
 22           //To call a timed task, i indicates that the task has no delay, s indicates that the task is executed every s milliseconds, and the trigger interval is calculated in milliseconds. 1 second = 1000 milliseconds. 
23          timer.schedule( new TimerAction(event), i, s);
 24        event.getServletContext().log("Task has 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 destroyed" ); 
 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");//可以改成new SimpleDateFormat("ss"),精确到秒
20             DateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
21             if(sdf.format(new Date()).equals("01")){// 每天凌晨01官网:www.fhadmin.org点
22                 Date beginDate = new Date();
23                 myevent.getServletContext().log("现在【"+myFormat.format(beginDate)+"】开始执行同步任务!");
24                 AllUserInfoMaintenance task = new AllUserInfoMaintenance();
25                 try {
26                     task.doUpdate();
27                     Date endDate = new Date();
28                     myevent.getServletContext().log("现在【"+myFormat.format(endDate)+"】执行同步任务结束!");
29                 } catch (SQLException e) {
30                     e.printStackTrace();
31                 }
32             }
33         }
34     
35 } 
 

3.在项目的web.xml中的<web-app>节点中加入以下内容(注意包的路径):

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

第一种方法就愉快官网:www.fhadmin.org 的搞完啦。
二、实现ApplicationListener<ContextRefreshedEvent>类

1.SrbaAutoTask类

 
 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("+++++++++++++++++++++++++++系统每天调度任务已开启,正在保护地球安全!++++++++++++++++++++++++++++");
27             int i=1000;       //1000毫秒及1秒
28             int s=1000*60*60; //每60分钟执行一次
29             Timer timer=new Timer();
30             timer.schedule(new TimerAction(event), i, s);
31         }
32     }
33 
34     
35 
36 
37 }
 

2.TimerAction()类,同一中的2。

3.配置applicationContext.xml 文件,增加以下内容(tomcat启动spring加载完成后,自动执行下面的类)

<!-- 自动扫描包com.srba.siss.rule.task,执行自动执行任务 -->
    <context:component-scan base-package="com.srba.siss.rule.task"></context:component-scan>

 第二种调度方法也愉快的配置完了。

Timer中的schedule()方法是有多种重载格式的,以适应不同的情况。该方法的格式如下:
 void schedule(TimerTask task, Date time)
           安排在指定的时间执行指定的任务。
 void schedule(TimerTask task, Date firstTime, long period)
           安排指定的任务在指定的时间开始进行重复的固定延迟执行。
 void schedule(TimerTask task, long delay)
           安排在指定延迟后执行指定的任务。
 void schedule(TimerTask task, long delay, long period)
           安排指定的任务从指定的延迟后开始进行重复的固定延迟执行。
Timer是线程安全的,此类可扩展到大量同时安排的任务(存在数千个都没有问题)。其所有构造方法都启动计时器线程。可以调用cancel() 终止此计时器,丢弃所有当前已安排的任务。purge()从此计时器的任务队列中移除所有已取消的任务。此类不提供实时保证:它使用 Object.wait(long) 方法来安排任务。
TimerTask是一个抽象类,由 Timer 安排为一次执行或重复执行的任务。它有一个抽象方法run()----计时器任务要执行的操作。因此,每个具体的任务类都必须继承TimerTask类,并且重写run()方法。另外它还有两个非抽象的方法:
 boolean cancel()
           取消此计时器任务。
 long scheduledExecutionTime()
           返回此任务最近实际 执行的安排 执行时间。

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326995641&siteId=291194637