When my scheduled periodic work request runs, it may be the case that I don't want it to do any work at that time, and just wait for the next in the periodic series.
At present I'm handling this by setting the Completer
to a success state and returning before firing the async work stuff, like so:
public ListenableFuture<Result> startWork() {
return CallbackToFutureAdapter.getFuture(completer -> {
if ( notThisTime() ) {
completer.set(Result.success());
return "nothing to do this time";
}
// the following will call completer.set(Result.success()) when it is finished...
startSomeAsyncStuff(completer);
return "started some async stuff";
});
}
Is this how it should be done? Or should I be running the notThisTime()
check before getFuture()
and returning a ListenableFuture
set to a completed stated, or something like that?
Yes, this is the correct way of doing things.
Unless you pull in all of Guava, the only way to create a ListenableFuture
object is via the CallbackToFutureAdapter.getFuture
, therefore you have to call that anyways to gain access to the completer
and to call set(Result.success())
.
Both startWork()
and the getFuture
lambda run on the main thread, so it is equally not safe do blocking work there, so you should make sure your notThisTime()
is safe to run on the main thread in either place.