Reputation: 4868
I have a question about a general design pattern in EJB. I hava Java EE application (EJBs and Web) and I need a kind of background process which is permanently scanning and processing specific data via JPA.
One solution, I think about, is to implement a @Singleton EJB. In a method annotated with @PostConstruct I can start my process.
@Singleton
@Startup
public class MyUpdateService {
@PostConstruct
void init() {
while(true) {
// scann for new data...
// do the job.....
}
}
}
But is this a recommended pattern? Or is there a better way to run such a class in an EJB Container?
In EJBs there are the other patterns like @TimerService and the new Java EE7 batch processing. But both concepts - I think - are used for finite Processes?
Upvotes: 0
Views: 449
Reputation: 4868
As an alternative to the TimerSerivce mentioned by @devmind since Java EE 7 it is possible to use the ManagedScheduledExecutorService:
@Startup
@Singleton
public class Scheduler {
static final long INITIAL_DELAY = 0;
static final long PERIOD = 2;
@Resource
ManagedScheduledExecutorService scheduler;
@PostConstruct
public void init() {
this.scheduler.scheduleAtFixedRate(this::invokePeriodically,
INITIAL_DELAY, PERIOD,
TimeUnit.SECONDS);
}
public void invokePeriodically() {
System.out.println("Don't use sout in prod " + LocalTime.now());
}
}
In difference to the TimerSerivce the ExecutorService can be run in parallel in separate tasks. See also a blog post form Adam Bien.
Upvotes: 1
Reputation: 364
Using EJB TimerService in current project for tasks like periodic data pruning, or back-end data synchronization. It allows not only single time execution, but also interval timers and timers with calendar based schedule.
Smth like:
@Startup
@Singleton
public class SyncTimer {
private static final long HOUR = 60 * 60 * 1000L;
@Resource
private TimerService timerService;
private Timer timer;
@PostConstruct
public void init() {
TimerConfig config = new TimerConfig();
config.setPersistent(false);
timer = timerService.createIntervalTimer(HOUR, HOUR, config);
}
@Timeout
private synchronized void onTimer() {
// every hour action
}
}
Upvotes: 3