I use the ScheduledExecutorService
to execute a task at a fixed rate. Here is the contents of my main method:
RemoteSync updater = new RemoteSync(config);
try {
updater.initialise();
updater.startService(totalTime, TimeUnit.MINUTES);
} catch (Exception e) {
e.printStackTrace();
}
RemoteSync
implements the AutoCloseable
(and Runnable
) interface, so I initially used try-with-resources
, like this:
try (RemoteSync updater = new RemoteSync(config)) {
...
} catch (Exception e) {
e.printStackTrace();
}
But updater.startService()
returns immediately after scheduling the task, so the updater.close()
is called prematurely and the application exits.
Here is the startService()
method of RemoteSync
:
public void startService(int rate, TimeUnit unit) {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
service =
scheduledExecutorService.scheduleWithFixedDelay(this, 1L,
rate,
unit);
}
Ideally, I would like to have a method like:
scheduledExecutorService.executeAtTermination(Runnable task)
This will allow me to call close()
when scheduler has actually stopped, unfortunately I am not aware of such a method.
What I can do, is block the startService()
method, with something like this:
while (!scheduledExecutorService.isTerminated()) {
Thread.sleep(10000);
}
but this feels dirty and hackish.
Any suggestion are welcome.