Web-TimeService用于定时调用(触发)应用,EJB2.1也提供了TimerService,但现在有的applicationserver不支持,有的就根本没有用到ejb,所以我写了一个简单的TimerSerivce
PublicclassTimerService
{
publicstaticfinallongp=1000*60*60;
Timertimer=newTimer(false);
TimerScheduleschedule=null;
publicTimerService()
{
}
publicvoidstart()throwsException
{
schedule=newTimerSchedule();
schedule.addTimerJob(newSomeTimerJob());
//addotherjobhere
timer.schedule(schedule,0,p);
}
publicvoidstop()throwsException
{
timer.cancel();
}
}
//包含了多个TimerJob,并每到一定时候取出来看看是否该调用
publicclassTimerScheduleextendsTimerTask
{
privateListlist=newArrayList();
publicTimerSchedule()
{}
publicvoidaddTimerJob(TimerJobjob)
{
list.add(job);
}
publicvoidrun()
{
Datenow=Calendar.getInstance().getTime();
Datenext=null;
for(inti=0;i<list.size();i
)
{
TimerJobjob=(TimerJob)list.get(i);
next=job.getNextExeDate();
if(isEquals(now,next))
{
job.execute();
}
}
}
/**
*比较俩个时间相差是否小于TimerService.p(一个周期)
*@paramnow
*@paramnext
*@return
*
/privatebooleanisEquals(Datenow,Datenext)
{
longtime=next.getTime()-now.getTime();
if(time<=TimerService.p&&time>=0)
{
returntrue;
}
else
{
returnfalse;
}
}
publicbooleancancel()
{
returntrue;
}
}
//该接口描述了如何完成TimerTask,请参考TimerJobExample
interfaceTimerJob
{
publicvoidexecute();
publicDategetNextExeDate();
}
/**
*该例子用于演示如何完成tiemrjob
*该例子功能是在每天的凌晨一点调用
*
/publicclassTimerJobExampleimplementsTimerJob
{
CalendarnextDate=null;
publicTimerJobExample()
{
nextDate=Calendar.getInstance();
nextDate.add(Calendar.DAY_OF_MONTH,1);
//将设置调用时间是(第二天的)每天凌晨1点
nextDate.set(Calendar.HOUR_OF_DAY,1);
}
publicvoidexecute()
{
nextDate.add(Calendar.DAY_OF_MONTH,1);
nextDate.set(Calendar.HOUR_OF_DAY,1);
callFunction();
}
publicDategetNextExeDate()
{
returnnextDate.getTime();
}
privatevoidcallFunction()
{
System.out.println("TimerJobExamplecallejbfuncation:" newDate());
}
}
启动Web_TimerService
启动Web-TimerService可以有多种方法,下面列出一个简单的方法,通过jsp来启动,停止TimerService
<@pagecontentType="text/html;charset=GBK">
<@pageimport="com.ted.cfioms.common.alert.*">
<
TimerServiceservice=(TimerService)application.getAttribute("timerService");
booleanisStart=true;
if(service==null)
{
service=newTimerService();
application.setAttribute("timerService",service);
service.start();
}
else
{
service.stop();
isStart=false;
service=null;
}
>
<html>
<head>
<title>
timerService
</title>
</head>
<bodybgcolor="ffffff">
<h1>
<=(isStart?"startok":"stopok")>
</h1>
</body>
</html>
简单吧,呵呵,我在网上没找到合适的TimerService,所以自己写的,如果大家有类似的代码,可以提出来参考参考,谢谢
一个简单的Timer Service
最新推荐文章于 2024-06-27 09:54:41 发布