Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set timer values in EJB scheduling?

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);
    }
 }
like image 345
Ruchira Gayan Ranaweera Avatar asked Apr 16 '26 19:04

Ruchira Gayan Ranaweera


1 Answers

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.

like image 89
Vegard Avatar answered Apr 18 '26 08:04

Vegard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!