示例代码:
@Singleton
@Startup public class EBlastScheduler {
@Resource
TimerService timerService;
EBlastScheduler what = new EBlastScheduler();
@PostConstruct
public void initialize(){
if (timerService.getTimers() != null) {
for (Timer timer : timerService.getTimers()) {
if (timer.getInfo().equals("EBlastScheduler")){
timer.cancel();
}
}
}
ScheduleExpression expression = new ScheduleExpression();
expression.second("*/1").minute("*").hour("*");
timerService.createCalendarTimer(expression);
}
@Timeout
public void execute(Timer timer){
System.out.println("----Invoked: " + System.currentTimeMillis());
} }
我只是想做一个定时器服务,如果设置了新的时间表,它可以通过取消以前的时间表来处理超时时间表的变化。就我而言,我不知道如何在 EJB 3.1 中执行此操作,尤其是因为我是这个框架的新手。非常感谢您的帮助。 :D
我想要这样的东西:
EBlastScheduler ebs = new EBlastScheduler(ScheduleExpression sExp); // this line of code must change the current scheduled time of the scheduler to the newly set'ed time.
注意:
I wanted to access this class remotely; and by passing new schedule as parameter/s, this class must change its timeout accordingly.
最佳答案
您可以拥有一个无状态的 bean,它可以用作管理系统中计时器的实用程序。它将负责对它们执行操作 - 创建/取消计时器。
目的是将定时器操作与启动类解耦,然后您可以在特定时间点修改它们。
但实用程序 bean 必须在 EBlastScheduler
之前初始化,这是一个启动 bean,因为您必须使用注释 @DependsOn("TimerUtilityBean")
对其进行注释。
下面是示例代码,可能需要一些修改。
EBlastScheduler.java
@Singleton
@Startup
@DependsOn("TimerUtilityBean")
public class EBlastScheduler {
@EJB
TimerUtilityBean timerBean;
@PostConstruct
public void initialize(){
timerBean.cancelTimer("EBlastScheduler");
timerBean.createTimer("*/1", "*", "*");
}
}
TimerUtilityBean.java
@Stateless
public class TimerUtilityBean {
@Resource
TimerService timerService;
public void createTimer(String sec, String min, String hour){
ScheduleExpression expression = new ScheduleExpression();
expression.second(sec).minute(min).hour(hour);
timerService.createCalendarTimer(expression);
}
public void cancelTimer(String timerInfo){
if (timerService.getTimers() != null) {
for (Timer timer : timerService.getTimers())
if (timer.getInfo().equals(timerInfo))
timer.cancel();
}
}
@Timeout
public void execute(Timer timer){
System.out.println("Invoked: " + System.currentTimeMillis());
}
public void reinitializeTimer(String sec, String min, String hour, String timerInfo){
cancelTimer(timerInfo);
createTimer(sec, min, hour);
}
}
现在,您可以使用 TimerUtilityBean
从应用程序中的任何位置管理计时器。可以远程访问它并且能够传递新的计划参数。
关于java - 如何让这个定时器服务类处理 "change in scheduled time"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8004293/