JAVA Web定时执行任务

JAVA Web定时执行任务

  1. 配置监听器

    在web.xml中添加监听器

    <listener>  
        <listener-class>com.aa.timer.TaskManagerlistener-class>  
    listener>

    监听类TaskManager

    import java.util.Calendar;
    import java.util.Timer;
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    import org.apache.commons.lang.time.DateUtils;
    
    public class TaskManager implements ServletContextListener{
         public  long t=DateUtils.MILLIS_PER_SECOND;
         /**  
          * 定时器  
          */  
        private Timer timer;  
        @Override
        public void contextDestroyed(ServletContextEvent sce) {
            // TODO Auto-generated method stub
            sce.getServletContext().log("[INFO]:timer shut down.");
        }
        @Override
        public void contextInitialized(ServletContextEvent sce) {
            // TODO Auto-generated method stub
            //定义定时器   
            sce.getServletContext().log("[INFO]:timer start.");  
            timer = new Timer("消息发送",true);    
            //启动备份任务,每月(4个星期)执行一次   
            //schedule(A,B,C) A:定时执行的函数,B:首次执行的时间(日期或延时) C:执行的时间间隔
            //timer.schedule(new MessagePusher(),t,30000); 
            timer.schedule(new MessagePusher(),t*10); 
        }
    }
  2. 配置定时器MessagePusher

import java.util.Date;
import java.util.TimerTask;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.zauther.weixin.service.ReminderService;

public class MessagePusher extends TimerTask{
    private static Logger logger = Logger.getLogger(MessagePusher.class);
    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println(new Date().toLocaleString());
        ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
        MessageSender messageSender=(MessageSender) ac.getBean("messageSender");
        messageSender.sendMessage();    
    }
}

你可能感兴趣的:(学习笔记)