在程序的编写过程中,大家一定遇到过这样的问题:在特定的某一时刻执行某项任务,或者在操作者操作后多长时间执行此项任务。这中功能到底是怎么实现的呢,下面我们探讨一下,在EJB3中,这中功能的实现方法。
在EJB3中,我们把这种功能称为定时服务;定时服务可以在stateless bean以及message driven bean中使用。stateless bean或者message driven bean定时器启动时,容器会从实例池中选择一个bean实例,然后调用其@Timeout方法。
利用TimeService来完成时间的设定,然后编写一个timeout时要执行的方法即可。显而易见,我们要编写完成一个定时服务,照理只需要两步:
①利用TimeService设定相应的时间;
②编写timeout方法,这个方法是达到TimeService设定的方法时执行的;
下面我们来看一个EJB例子,这个例子设定在EJB执行20秒后,打印出三行字:
@Stateless
@Remote(TimerServiceBean.class)
public class TimerServiceImpl implements TimerServiceBean {
@Resource
private TimerService timerService;
public void scheduleTimer(long millstimes) {
timerService.createTimer(20000, null);
}
@Timeout
public void timeoutHandler(Timer timer) {
System.out.println("timer out start");
System.out.println("timer out is execute");
System.out.println("timer out end");
}
}
执行时,我们必须执行scheduleTimer方法,设定一个20秒的定时器;20秒后,会自动执行@Timeout标注的方法,打印出三行字。EJB3中使用TimeService,只需要注入即可,也可以利用sessionContext来创建TimeService。
要使用定时服务,我们需要在方法中,创建一个定时器,timerService.createTimer(20000, null);这行代码就创建了一个20秒的定时器。20秒后触发。
然后我们需要创建一个方法来设定,20秒到了之后,应该做些什么,方法的名字可以随便起,但是必须遵循两条,①必须用@Timeout来标记;②方法必须符合public void XXXXX(Timer timer);
在本例中,@timeout所标注的方法打印了三行文字。