@Schedule
用于容器在部署期间创建的自动计时器。
另一方面,可以使用TimerService
它允许您在运行时定义何时@Timeout
应调用该方法。
这可能是您感兴趣的材料:Java EE 6教程-使用Timer Service。
只是为了使这个答案更完整。如果这是一个问题, 那么 答案是否可能- 是的。
有一种方法可以更改由创建的自动计时器的参数@Schedule
。然而,这是非常 -它取消了自动计时器并创建了类似的程序化计时器:
// Automatic timer - run every 5 seconds
// It's a automatic (@Schedule) and programmatic (@Timeout) timer timeout method
// at the same time (which is UNUSUAL)
@Schedule(hour = "*", minute = "*", second = "*/5")
@Timeout
public void myScheduler(Timer timer) {
// This might be checked basing on i.e. timer.getInfo().
firstSchedule = ...
if (!firstSchedule) {
// ordinary code for the scheduler
} else {
// Get actual schedule expression.
// It's the first invocation, so it's equal to the one in @Schedule(...)
ScheduleExpression expr = timer.getSchedule();
// Your new expression from Now on
expr.second("*/7");
// timers is TimerService object injected using @Resource TimerService.
// Create new timer based on modified expression.
timers.createCalendarTimer(expr);
// Cancel the timer created with @Schedule annotation.
timer.cancel();
}
}
再说一次-就我个人而言,我永远不会使用这样的代码,也永远不想在真实的项目中看到类似的东西:-)定时器是: