简单的定时任务(项目发布时启动,停止时任务结束)

有时候想在项目启动时,添加一个简单的定时任务,下面则是简单的代码实现。
1. Task.java 定时任务类

package com.sun4j.main;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class Task {

    private static int interval = 60;
    private static Timer timer = null;
    private static TimerTask timerTask = null;
    private static SimpleDateFormat format = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");

    /** * 定时更新AccessToken */
    public static void OnStartAccessToken(int autoScends) {
        if (autoScends == 0) {
            autoScends = interval;
        }
        Date autoTime = new Date();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                System.out.println("定时更新AccessToken开始执行时间: "
                        + format.format(new Date()));
                String token=AccessToken.getAccessToken("wx6a5df0cf975d7d2a","Lc3MGoivBYO1YkXrdbzibs3BCpsztE_yBpIN9PFUopfQY0TTuS2KwStR3JyKT1gj" , 1);
                System.out.println("token="+token);
            }
        };
        timer = new Timer();
        timer.scheduleAtFixedRate(timerTask, autoTime, autoScends * 1000);// 每隔7000秒执行一次
    }

    /** * 关闭定时更新AccessToken */
    public static void OnStopAccessToken() {
        if (timerTask != null) {
            timerTask.cancel();
        }

        if (timer != null) {
            timer.cancel();
        }
    }
}
  1. MyContextListener.java
package com.sun4j.main;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MyContextListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent ev) {
        System.out.println("启动定时更新token...");
        Task.OnStartAccessToken(10);
    }

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        System.out.println("关闭定时更新token...");
        Task.OnStopAccessToken();
    }

}
  1. web.xml文件配置
<!-- 下面是配置上下文的监听器,在监听器中完成任务的注册和撤销 -->
<listener>
    <listener-class>ice.stream.main.MyContextListener</listener-class>
</listener>
</web-app>

你可能感兴趣的:(定时任务-task)