Wednesday 1 August 2018

Nightly scheduler in OSGI bundles

I have faced some difficulties while i was implementing nightly scheduler job in Osgi bundles.
So thought of sharing solutions which worked for me.

I had a requirement where job has to get execute at 12:00 am EST.I have used ScheduledExecutorService for running job.

In start method of osgi bundles i have implemented job like below,

ZoneId newYokZoneId = ZoneId.of("America/New_York");
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();  
Long midnight=ZonedDateTime.now(newYokZoneId).until(ZonedDateTime.now(newYokZoneId).toLocalDate().plusDays(1).atStartOfDay(newYokZoneId).plusMinutes(1), ChronoUnit.MINUTES);
service.scheduleAtFixedRate(runnable, midnight, TimeUnit.DAYS.toMinutes(1), TimeUnit.MINUTES);


I was facing problem like, on each start of the bundle new thread was getting created and job was executing by multiple threads.

One mistake i have done over here is, i have not shutdown the schedulerExecutorService that was causing the multiple threads in jvm.

if service.shutdown(); is called the periodic scheduler will never be executed.

To resolve the issue i have added below mentioned code in bundle stop method.

if (service != null)
try {
service.shutdown();
final long thirty = 30;
final TimeUnit seconds = TimeUnit.SECONDS;
boolean cleanTermination = service.awaitTermination(thirty, seconds);
} catch (final InterruptedException e) {
LOG.error("SchedularJob Executor interrupted.", e);
Thread.currentThread().interrupt();
}

NOTE : call executor service shutdown method in any stop method of container or bundle.