欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java定时器

程序员文章站 2023-12-21 21:43:46
...
1:

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class DingShi implements ServletContextListener
{
private java.util.Timer timer = null;

public void contextInitialized(ServletContextEvent event)
{
timer = new java.util.Timer(true);
event.getServletContext().log("定时器已启动");
System.out.println("启动");
//每小时刷新
timer.schedule(new MyTask(event.getServletContext()), 0,60*60*1000);
event.getServletContext().log("已经添加任务调度表");
}

public void contextDestroyed(ServletContextEvent event)
{
timer.cancel();
event.getServletContext().log("定时器销毁");
}

}

2:

import java.util.TimerTask;
import javax.servlet.ServletContext;
public class MyTask extends TimerTask
{
private static boolean isRunning = false;

private ServletContext context = null;

public MyTask(ServletContext context)
{
this.context = context;
}

public void run()
{
if (!isRunning)
{
isRunning = true;
context.log("开始执行指定任务");
//你要定时执行的方法
//NewsDaoImp nd = new NewsDaoImp();
//nd.dingshiTest();
isRunning = false;
context.log("指定任务执行结束");
}
else
{
context.log("上一次任务执行还未结束");
}
}

}

3:web.xml配置文件中添加
<listener>
<listener-class>cn.com.sns.www.view.DingShi</listener-class>
</listener>

上一篇:

下一篇: