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

对于有ejb经验的人来说可能是一个愚蠢的问题……

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

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

@Schedule用于在部署期间由容器创建的自动计时器。

另一方面,您可以使用TimerService ,它允许您在运行时定义应该调用@Timeout方法。

这可能是您的有趣材料: Java EE 6教程 – 使用定时服务 。

编辑:只是为了让这个答案更完整。 如果这是一个问题, 那么答案是可能的 – 是的,是的。

有一种方法可以“改变@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 ie 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中定义它们来创建,
  • 程序化并由应用程序代码创建,该代码在运行时可以具有不同的值。