java定时器(不废话,直接讲例子)

时间:2022-08-07 20:03:13
 

该类继承timerTask 里面的run方法写具体的方法比如调用数据库之类的

package com.sys.tasktimer;
import java.util.TimerTask;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
public class TimerSendEmail extends TimerTask {
 public TimerSendEmail() {
  super();
  // TODO Auto-generated constructor stub
 }
 private static final int C_SCHEDULE_HOUR = 3;// 这个代表3点钟的时候执行任务
 private static boolean isRunning = false;
 private ServletContext context = null;
 public TimerSendEmail(ServletContext context) {
  this.context = context;
 }
 public void run() {
   System.out.println("===================");
 }
 public void init() throws ServletException {
  // Put your code here
 }
}
该类是监听类,这个类需要在web.xml里面配置,从而在tomcat启动的时候去调用

package com.sys.tasktimer;

import java.util.Timer;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpServlet;

public class TimerSendEmailListener extends HttpServlet implements ServletContextListener {
    private Timer timer = null;
    public void contextInitialized(ServletContextEvent event) {
      timer = new Timer(true);
      event.getServletContext().log("发送邮件定时器已启动");
      timer.schedule(new TimerSendEmail(event.getServletContext()),0,1000); //0表示tomcat启动的时候运行切不延迟,1000表示运行周期为1秒

 event.getServletContext().log("发送邮件已经添加任务调度表");
    }
    public void contextDestroyed(ServletContextEvent event) {
      timer.cancel();
      System.out.println("发送邮件定时器销毁");
      event.getServletContext().log("发送邮件定时器销毁");
    }
}
web.xml配置如下,配置TimerSendEmailListener 这个类

 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 <listener>
<listener-class>com.sys.tasktimer.TimerSendEmailListener</listener-class>
</listener>

说明:这个例子拿下来可以直接用