最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
JAVA WEB程序中添加定时器
时间:2010-02-28 编辑:简简单单 来源:一聚教程网
这是我的定时器类,用来定时执行某段任务;
package com.my.time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
public class BugXmlTimer {
public Timer timer;
public void timerStart(){
timer = new Timer();
Date datetime=new Date();
Date midnightDate=new Date();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
midnightDate = sdf2.parse(sdf1.format(datetime)+" 23:00:00");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long in=midnightDate.getTime()-datetime.getTime();
System.out.println("before task");
//立刻执行,然后每隔30s执行一次
timer.schedule(new BugXmlTimerTask(), 0,30000);
}
public void timerStop(){
if(timer!=null)
timer.cancel();
}
public static void main(String[] args){
BugXmlTimer myTimer=new BugXmlTimer();
// TODO Auto-generated method stub
myTimer.timerStart();
}
}
//这是执行任务的类,即每隔一段时间要做的事情在这里
package com.my.time;
import java.util.TimerTask;
public class BugXmlTimerTask extends TimerTask {
@Override
public void run() {
System.out.print("run task");
}
}
//以下是出发定时操作的类,该类实现了ServletContextListener
public class MyTimerListener implements ServletContextListener {
private BugXmlTimer mytimer = new BugXmlTimer ();
public void contextInitialized(ServletContextEvent event) {
mytimer.timerStart();
}
public void contextDestroyed(ServletContextEvent event) {
mytimer.timerStop();
}
}
然后在web.xml里部署一下,即可在程序启动后运行定时器了!
-
下一个: JAVA中集合数组的输出方法
相关文章
- 安装程序出现禁止进行安装解决方法 11-10
- CMD命令怎么结束程序 结束程序的方法 06-19
- 中国银行牌价小程序在哪 中国银行牌价小程序位置介绍 04-07
- 小睡眠app有用吗?小睡眠app小程序有什么用 03-09
- 摩拜单车小程序入口在哪 02-24
- 摩拜单车小程序怎么退押金 摩拜单车小程序需要押金吗 02-24