小编典典

可以在运行时为@Schedule注释更改ejb参数吗?

java

对于拥有ejb经验的人来说,这可能是一个愚蠢的问题。

我想动态地读取和更改我的其中一个通过@Schedule注释使用Java EE调度程序的EJB
Bean的分钟参数。有人知道如何在运行时执行此操作,而不是像在下面的类中对其进行硬编码?如果我要以编程方式进行操作,是否仍可以使用@Schedule注释?

 @Schedule(dayOfWeek = "0-5", hour = "0/2", minute = "0/20", timezone = "America/Los_Angeles")
 private void checkInventory() {
 }

阅读 246

收藏
2020-12-03

共1个答案

小编典典

@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();
    }
}

再说一次-就我个人而言,我永远不会使用这样的代码,也永远不想在真实的项目中看到类似的东西:-)定时器是:

  • 自动 ,是通过@Schedule对值进行硬编码或在ejb-jar.xml中定义它们来创建的,
  • 程序化的 ,由应用程序代码创建,该代码在运行时可以具有不同的值。
2020-12-03