JAVA WEB 定时任务TimeTask

2023-12-13 03:52:09

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();
        }
    }
}

文章来源:https://blog.csdn.net/qq_39213969/article/details/134930045
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。