通过定时器进行任务的执行是比较常见的情况,下面的是个简单的示例:
主要借助于监听器和TimerTask和Timer类进行实现,另外spring提供了定时器的高级实现好像是quarts。
package com.rx.timer;
import java.util.Date;
import java.util.TimerTask;
public class MyTask extends TimerTask {
@Override
public void run() {
System.out.println("call at " + (new Date()));
}
}
package com.rx.timer;
import java.util.Timer;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyListen implements ServletContextListener {
private Timer timer = null;
@Override
public void contextDestroyed(ServletContextEvent arg0) {
timer.cancel();
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
timer = new Timer(true);
//设置任务计划,启动和间隔时间
timer.schedule(new MyTask(), 0, 1000 * 10);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>
WebTimer</display-name>
<listener>
<listener-class>com.rx.timer.MyListen</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
嗯...再转个复杂点的!和上面基本相同,但是在任务执行控制上更细致了
public class WorkServiceImpl implements WorkService , ServletContextListener{
public void contextDestroyed(ServletContextEvent arg0){
timer.cancel();
System.out.println("定时器已销毁");
}
public void contextInitialized(ServletContextEvent event){
timer = new java.util.Timer(true);
sampleTask = new SampleTask(event.getServletContext());
System.out.println("定时器已启动");
timer.schedule(sampleTask, 0, 60 * 60 * 1000);
System.out.println("已经添加任务调度表");
}
}
class SampleTask extends TimerTask{
private ServletContext context;
private static boolean isRunning = false; //是否在运行
private static boolean flag = true; //跑过一次就不跑了
private static final int C_SCHEDULE_HOUR = 23; //运行时间
private WorkServiceImpl workService;
public SampleTask(ServletContext context){
this.context = context;
}
public void run() {
workService = new WorkServiceImpl();
Calendar cal = Calendar.getInstance();
if (!isRunning){
if (C_SCHEDULE_HOUR == cal.get(Calendar.HOUR_OF_DAY) && flag){
isRunning = true;
workService.autoWorkOff();
isRunning = false;
flag = false;
context.log("指定任务执行结束");
}
} else{
context.log("上一次任务执行还未结束");
}
if(C_SCHEDULE_HOUR != cal.get(Calendar.HOUR_OF_DAY)){
flag = true;
}
}
}
在web.xml中配置,如下:
<listener>
<listener-class>com.css.wam.service.impl.WorkServiceImpl</listener-class>
</listener>