JAVA WEB 定时任务TimeTask

web.xml

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
    <display-name>Archetype Created Web Application</display-name>
    <listener>
        <listener-class>task.SendWsListener</listener-class>
    </listener>

</web-app>

listener(SendWsListener)

package task;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
 
public class SendWsListener implements ServletContextListener  {
 
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("定时任务已启动");
        new TimerManager();
    }
 
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("定时任务已销毁");
    }
}

TimerManager

package task;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
 
public class TimerManager {
 
    //时间间6个月
    //private static final long PERIOD_DAY = 6 * 30 * 24 * 60 * 60 * 1000L;

    private static final long PERIOD_DAY = 1000L;

    public TimerManager() {
        Calendar calendar = Calendar.getInstance();
 
        //定制每日7点00执行
        calendar.set(Calendar.HOUR_OF_DAY, 15);
        calendar.set(Calendar.MINUTE, 32);
        calendar.set(Calendar.SECOND, 0);
        //第一次执行定时任务的时间
        Date date = calendar.getTime();
        //如果当前时间已经过去所定时的时间点,则在第二天时间点开始执行
        if (date.before(new Date())) {
            date = this.addDay(date, 1);
        }
        Timer timer = new Timer();
        TimerTaskService task = new TimerTaskService();
        //安排指定的任务在指定的时间开始进行重复的固定延迟执行。
        timer.schedule(task, date, PERIOD_DAY);
    }
 
    // 增加或减少天数
    private Date addDay(Date date, int num) {
        Calendar startDt = Calendar.getInstance();
        startDt.setTime(date);
        startDt.add(Calendar.DAY_OF_MONTH, num);
        return startDt.getTime();
    }
}

TimerTaskService

package task;

import utils.FileCleaner;

import java.util.HashMap;
import java.util.Map;
import java.util.TimerTask;

public class TimerTaskService extends TimerTask {

    @Override
    public void run() {
        try {
            System.out.println("定时任务开始执行");
            //主要业务逻辑
            Map<String, String> maps = new HashMap<>(2);
            maps.put("source", "/root/xxx/source/");
            maps.put("target", "/root/xxx/target/");
            FileCleaner.fileClean(maps);
            //TO DO
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(java技术开发学习,java,开发语言,TimeTask,定时任务,JAVAWEB)