How to set timer values in EJB scheduling?

2k views Asked by At

Currently I am using following configuration to schedule my scheduler.

 @Schedule(second ="1/10", minute = "*", hour = "*")
 private void scheduleUser() {      
    try {
        new UserFacade().insertUserInfo();            
    } catch (Exception e) {
        logger.error("Error in : " + e);
    }
 }

Now I want to set timer value in run time not in hard coded way. Let say I have a bean call Property and it has a field called frequency.

Now I want to set values like new Property().getFrequency() for EJB scheduler.

Is there any way to do some thing like following?

 @Schedule(second =new Property().getFrequency(), minute = "*", hour = "*")
 private void scheduleUser() {      
    try {
        new UserFacade().insertUserInfo();            
    } catch (Exception e) {
        logger.error("Error in : " + e);
    }
 }
2

There are 2 answers

0
Vegard On

Not with annotations, no. You have to use programmatic timers (Java 7, EE7):

package com.foo;

import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.EJBException;
import javax.ejb.Singleton;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerService;

@Singleton
public class MyTimer {
    @Resource
    private TimerService timerService;

    @Timeout
    public void timeout(Timer timer) {
        System.out.println("TimerBean: timeout occurred");
    }

    public void schedule(Date start, long intervalMilis) {
        try{
            timerService.createTimer(start, intervalMilis, "my timer");            
        } catch (EJBException|IllegalArgumentException|IllegalStateException ex)  {
            Logger.getLogger(MyTimer.class.getName()).log(Level.WARNING, ex.getMessage(), ex);
        }
    }
}

See https://docs.oracle.com/javaee/7/tutorial/ejb-basicexamples004.htm for further information.

0
Dan Abel On

Similar to Vegard's submitted answer except this one using ScheduleExpression. More info Beginning Java EE 7 book

import javax.ejb.ScheduleExpression;

@Singleton
public class MyTimer {

    @Resource
    private TimerService timerService;

    @Timeout
    public void timeout(Timer timer) {
        System.out.println("TimerBean: timeout occurred");
    }

    public void schedule(String DOW, String H, String M, String S) {
        try{
            ScheduleExpression scheduleExpression = new ScheduleExpression();
            scheduleExpression.dayOfWeek(DOW); 
            scheduleExpression.hour(H); 
            scheduleExpression.minute(M); 
            scheduleExpression.second(S); 

            timerService.createCalendarTimer(scheduleExpression, new TimerConfig(this, false));
        } catch (EJBException|IllegalArgumentException|IllegalStateException ex)  {
            Logger.getLogger(MyTimer.class.getName()).log(Level.WARNING, ex.getMessage(), ex);
        }
    }

}