Possible to change ejb parameter at runtime for @Schedule annotation?

后端 未结 1 1982
慢半拍i
慢半拍i 2021-02-05 10:15

Probably a silly question for someone with ejb experience...

I want to read and change the minute parameter dynamically for one of my EJB beans that uses the Java EE sc

1条回答
  •  不知归路
    2021-02-05 11:09

    @Schedule is for automatic timers created by the container during deployment.

    On the other hand, you can use TimerService which allows you to define at runtime when the @Timeout method should be called.

    This might be interesting material for your: The Java EE 6 Tutorial - Using the Timer Service.

    EDIT: Just to make this answer more complete. If it's a matter of is it possible than the answer would be - yes, it is.

    There is a way to "change the parameters" of automatic timer created with @Schedule. Nevertheless it's quite extraordinary - it cancels the automatic timer and creates a similar programmatic one:

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

    Once again - personally, I would never use such code and would never want to see anything like this in a real project :-) Either the timer is:

    • automatic and is created by @Schedule by hard-coding the values or by defining them in ejb-jar.xml,
    • programmatic and is created by the application code which can have different values in the runtime.

    0 讨论(0)
提交回复
热议问题