Web-TimeService用於定時調用(觸發)應用,EJB2.1也提供了TimerService,但現在有的application server不支持,有的就根本沒有用到ejb,所以我寫了一個簡單的TimerSerivce
Public class TimerService
{
public static final long p = 1000*60*60;
Timer timer = new Timer(false);
TimerSchedule schedule = null;
public TimerService()
{
}
public void start() throws Exception
{
schedule = new TimerSchedule();
schedule.addTimerJob(new SomeTimerJob());
//add other job here
timer.schedule(schedule,0,p);
}
public void stop() throws Exception
{
timer.cancel();
}
}
//包含了多個TimerJob,並每到一定時候取出來看看是否該調用
public class TimerSchedule extends TimerTask
{
private List list = new ArrayList();
public TimerSchedule()
{}
public void addTimerJob(TimerJob job)
{
list.add(job);
}
public void run()
{
Date now = Calendar.getInstance().getTime();
Date next = null;
for(int i=0;i<list.size();i++)
{
TimerJob job = (TimerJob)list.get(i);
next = job.getNextExeDate();
if(isEquals(now,next))
{
job.execute();
}
}
}
/**
* 比較倆個時間相差是否小於TimerService.p(一個周期)
* @param now
* @param next
* @return
*/
private boolean isEquals(Date now,Date next)
{
long time = next.getTime()-now.getTime();
if (time <= TimerService.p && time >= 0)
{
return true;
}
else
{
return false;
}
}
public boolean cancel()
{
return true;
}
}
//該接口描述了如何完成TimerTask,請參考TimerJobExample
interface TimerJob
{
public void execute();
public Date getNextExeDate();
}
/**
* 該例子用於演示如何完成tiemrjob
* 該例子功能是在每天的凌晨一點調用
*/
public class TimerJobExample implements TimerJob
{
Calendar nextDate = null;
public TimerJobExample()
{
nextDate = Calendar.getInstance();
nextDate.add(Calendar.DAY_OF_MONTH,1);
//將設置調用時間是(第二天的)每天凌晨1點
nextDate.set(Calendar.HOUR_OF_DAY,1);
}
public void execute()
{
nextDate.add(Calendar.DAY_OF_MONTH,1);
nextDate.set(Calendar.HOUR_OF_DAY,1);
callFunction();
}
public Date getNextExeDate()
{
return nextDate.getTime();
}
private void callFunction()
{
System.out.println("TimerJobExample call ejb funcation:"+new Date());
}
}
啟動Web_TimerService
啟動Web-TimerService可以有多種方法,下面列出一個簡單的方法,通過jsp來啟動,停止TimerService
<%@ page contentType="text/html; charset=GBK" %>
<%@ page import="com.ted.cfioms.common.alert.*"%>
<%
TimerService service = (TimerService)application.getAttribute("timerService");
boolean isStart = true;
if(service == null)
{
service = new TimerService();
application.setAttribute("timerService",service);
service.start();
}
else
{
service.stop();
isStart = false;
service = null;
}
%>
<html>
<head>
<title>
timerService
</title>
</head>
<body bgcolor="#ffffff">
<h1>
<%=(isStart?"start ok":"stop ok")%>
</h1>
</body>
</html>
簡單吧,呵呵,我在網上沒找到合適的TimerService,所以自己寫的,如果大家有類似的代碼,可以提出來參考參考,謝謝