java定时器使用

时间:2021-05-24 00:21:12

//先弄一个Task

public class DbBackUpRestore  extends  TimerTask {
private static Log log = LogFactory.getLog(DbBackUpRestore.class);
@Override
public void run() {

               log.info("做你的任务");

        }

}

//然后弄一个监听器,通过Timer定时执行任务

public class BackUpListener implements ServletContextListener {


private Timer timer = null;

/*
* @Title: contextInitialized 
* @Description: 
* @param arg0  
* @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent) 
*/
@Override
public void contextInitialized(ServletContextEvent arg0) {
timer= new Timer(true);
//设置任务计划,启动和间隔时间
timer.schedule(new DbBackUpRestore(), 0, 1000*60);
}

/*
* @Title: contextDestroyed 
* @Description: 
* @param arg0  
* @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent) 
*/
@Override
public void contextDestroyed(ServletContextEvent arg0) {
        timer.cancel();
}

}

//在全局配置文件web.xml中任何位置配置监听器

<!-- 定时备份的监听器 -->
    <listener>
        <listener-class>listener.BackUpListener</listener-class>
    </listener>