Skip to content

Instantly share code, notes, and snippets.

@zagorulkinde
Created February 28, 2019 11:41
Show Gist options
  • Save zagorulkinde/8ad0ef2e3cb15d0409e9331ce78dc8e1 to your computer and use it in GitHub Desktop.
Save zagorulkinde/8ad0ef2e3cb15d0409e9331ce78dc8e1 to your computer and use it in GitHub Desktop.
Restart runnable if error occurred and after deadline
private void start(Runnable consumer, long initialDelay, int step) {
LOG.info("launching consumer {} ...", consumer.getClass().getCanonicalName());
CompletableFuture<Object> promise = new CompletableFuture<>();
LOG.info("delayed with: {}", initialDelay + step);
scheduler.schedule(() -> promise.complete(null), initialDelay + step, TimeUnit.SECONDS);
// waiting when promise completes
CompletableFuture<Void> voidCompletableFuture = promise.thenRunAsync(consumer, executor)
.exceptionally((t) -> {
LOG.error("error h", t);
return null;
})
.whenComplete((v, t) -> {
// resubmit task
LOG.info("restarting consumer {} ...", consumer.getClass().getCanonicalName());
start(consumer, initialDelay + step, step);
});
scheduler.schedule(() -> {
// stop
voidCompletableFuture.cancel(true);
// start
start(consumer, initialDelay + step, step);
}, 24, TimeUnit.HOURS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment