我创建了一个包含EJB的测试应用程序,它应该每秒打印当前的Timestamp。现在,在我的wildfly上部署Web应用程序之后,我每秒钟会收到大约5条日志消息......看起来正在运行多个调度程序,这会触发输出......
你有任何想法,如何解决?如果我只是使用@Schedule注释方法,它会每秒打印一次结果,但通过以编程方式设置计时器会产生问题:
@Singleton
@Startup
public class Scheduler {
@Resource
TimerService timerService;
@Inject
Logger logger;
@Timeout
public void doStuff() {
logger.info("Programmatic Scheduler: " + System.currentTimeMillis());
}
@PostConstruct
public void startScheduler() {
TimerConfig timerConfig = new TimerConfig();
timerConfig.setPersistent(false);
ScheduleExpression expression = new ScheduleExpression();
expression.second("*/1").minute("*").hour("*");
timerService.createCalendarTimer(expression, timerConfig);
}
}
...这是输出 - 你看,每秒多次打印:
16:26:46,574 INFO [de.hays.liferay.schedulerprogrammatically.Scheduler] (EJB default - 10) Programmatic Scheduler: 143455120657
16:26:46,849 INFO [de.hays.liferay.schedulerprogrammatically.Scheduler] (EJB default - 8) Programmatic Scheduler: 1434551206849
16:26:46,869 INFO [de.hays.liferay.schedulerprogrammatically.Scheduler] (EJB default - 7) Programmatic Scheduler: 1434551206869
16:26:46,890 INFO [de.hays.liferay.schedulerprogrammatically.Scheduler] (EJB default - 4) Programmatic Scheduler: 1434551206890
16:26:47,083 INFO [de.hays.liferay.schedulerprogrammatically.Scheduler] (EJB default - 3) Programmatic Scheduler: 1434551207083
16:26:47,145 INFO [de.hays.liferay.schedulerprogrammatically.Scheduler] (EJB default - 1) Programmatic Scheduler: 1434551207145
16:26:47,185 INFO [de.hays.liferay.schedulerprogrammatically.Scheduler] (EJB default - 9) Programmatic Scheduler: 1434551207185
16:26:47,246 INFO [de.hays.liferay.schedulerprogrammatically.Scheduler] (EJB default - 6) Programmatic Scheduler: 1434551207246
16:26:47,274 INFO [de.hays.liferay.schedulerprogrammatically.Scheduler] (EJB default - 2) Programmatic Scheduler: 1434551207274
16:26:47,489 INFO [de.hays.liferay.schedulerprogrammatically.Scheduler] (EJB default - 5) Programmatic Scheduler: 1434551207489
答案 0 :(得分:2)
我知道了 - 我查看了野生苍蝇上正在运行的计时器的java任务控制 - 并且有多个计时器。
所以我编辑了我的代码,杀死应用程序的所有现有计时器,然后创建一个计时器,以确保,实际上只有一个计时器:
@PostConstruct
public void startScheduler() {
TimerService timerService = sessionContext.getTimerService();
logger.info("Current running timers: {}", timerService.getTimers().toString());
for (Timer t : timerService.getTimers()) {
t.cancel();
logger.info("killed the timer service: {}", t);
}
TimerConfig timerConfig = new TimerConfig();
timerConfig.setPersistent(false);
Timer createdIntervalTimer = sessionContext.getTimerService().createIntervalTimer(0, 5000, timerConfig);
logger.info("Created new Timer: {}", createdIntervalTimer);
}
答案 1 :(得分:0)
您不会显示您的包裹进口。 javax.inject.Singleton
将解释行为,被EJB忽略。 javax.ejb.Singleton
就是你想要的那个。