简体   繁体   English

使用EJB计时器的Java EE计划程序任务

[英]Java EE Scheduler Task using EJB Timers

I've a requirement which requires 3-6 scheduled task to run at a given time of the day. 我有一项要求,要求在当天的给定时间运行3-6个计划任务。 I am completely new to EJB timers, but have read that EJB timers is the best way to handle scheduled task in a Java EE container. 我是EJB计时器的新手,但已经读过EJB计时器是处理Java EE容器中的计划任务的最佳方法。

Design Question: 设计问题:

Let's say I need 10 scheduled tasks. 假设我需要10个预定任务。 I don't want to have, if possible, 10 EJB timers created. 如果可能的话,我不希望创建10个EJB计时器。 Instead I would like to have a one off EJB timer created and then reuse this for creating as much scheduled jobs as requried, passing the scheduled time to run (as aruguements) for each instance, to is this possible? 相反,我希望创建一个关闭的EJB计时器,然后重新使用它来创建所需的预定作业,为每个实例传递预定的运行时间(作为aruguements),这可能吗? Can someone please help with a skeleton code on this please? 请有人请帮助解决这个问题吗?

NB I am thinking of using non-persistent EJB timers ... NB我在考虑使用非持久性EJB计时器......

Another option (in addition to alreay said) is to use singleton with @Schedule annotation for each of your timed methods: 另一个选项(除了alreay说)是为每个定时方法使用带有@Schedule注释的单例:

@Singleton
@Startup
public class TimedTaskManager {

  @Schedule(second = "0", minute = "*/5", hour = "*")
  public void runTask1() {
    //
  }

  @Schedule(second = "15", minute = "*/5", hour = "6,7,8")
  public void runTask2() {
    //
  }

  //
  //

  @Schedule(second = "0", minute = "*", hour = "1,2,6")
  public void runTaskN() {
    //
  }
}

You could define a timer in one of your stateless/message driven bean business methods (you'd still have to call it, though, it's not possible to create a timer that would start off on its own). 你可以在一个无状态/消息驱动的bean业务方法中定义一个定时器(你仍然需要调用它,但是,不可能创建一个自己启动的定时器)。 Then, in the @Timeout method you could recreate the timer based on any logic you find suitable, ie 然后,在@Timeout方法中,您可以根据您认为合适的任何逻辑重新创建计时器,即

@Stateless
public SomeEJB ... {

     @Resource
     private TimerService timerService;

     public void businessMethod() {
         timerService.createTimer(...);
     }

     @Timeout
     public void timeout(Timer timer) {
         // do some timer-related logic, recreate the timer,
         // perhaps with new duration
         timerService.createTimer(...);
     }
}

This example is EJB 3.0-compatible. 此示例与EJB 3.0兼容。

AFAIK it isn't possible to create one 'reusable' timer in an EJB beacuse you have to tell each timer which method should be invoked. AFAIK无法在EJB中创建一个“可重用”计时器,因为您必须告诉每个计时器应该调用哪个方法。

Have a look at this: 看看这个:

The 3rd party library Quartz Scheduler should be capable of creating Timer-objects programmatically. 第三方库Quartz Scheduler应该能够以编程方式创建Timer对象。 Maybe its worth to have a look at this! 也许值得一看这个!

Hope this helped, have Fun! 希望这有帮助,玩得开心!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM