Skip to content

Instantly share code, notes, and snippets.

@ldaley
Created April 8, 2016 00:11
Show Gist options
  • Save ldaley/a3e3253e9b7b0a4ccae466eecb0ca0dd to your computer and use it in GitHub Desktop.
Save ldaley/a3e3253e9b7b0a4ccae466eecb0ca0dd to your computer and use it in GitHub Desktop.
Periodic background jobs in Ratpack
import ratpack.exec.ExecController;
import ratpack.exec.Execution;
import ratpack.http.client.HttpClient;
import ratpack.server.RatpackServer;
import ratpack.service.Service;
import ratpack.service.StartEvent;
import ratpack.service.StopEvent;
import java.net.URI;
import java.util.Optional;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class Example {
static class ScheduledService implements Service {
private volatile ScheduledFuture<?> nextFuture;
private volatile boolean stopped;
private HttpClient httpClient;
private ScheduledExecutorService executorService;
@Override
public void onStart(StartEvent event) throws Exception {
httpClient = event.getRegistry().get(HttpClient.class);
executorService = event.getRegistry().get(ExecController.class).getExecutor();
scheduleNext();
}
@Override
public void onStop(StopEvent event) throws Exception {
stopped = true;
Optional.ofNullable(nextFuture).ifPresent(f -> f.cancel(true));
}
private void scheduleNext() {
nextFuture = executorService.schedule(this::run, 1, TimeUnit.SECONDS);
}
private void run() {
if (stopped) {
return;
}
Execution.fork()
.onComplete(e -> scheduleNext())
.onError(Throwable::printStackTrace)
.start(e ->
httpClient.get(new URI("https://google.com")).then(response ->
System.out.println("Status: " + response.getStatusCode())
)
);
}
}
public static void main(String[] args) throws Exception {
RatpackServer server = RatpackServer.of(s -> s
.registryOf(r -> r.add(new ScheduledService()))
);
server.start();
Thread.sleep(5000);
server.stop();
}
}
@michalmela
Copy link

Interestingly, it seems that if you edit this example live in development mode (I checked with a minimal ratpack.groovy script) the onStop never gets called. I found an ugly workaround (it's for a mock application anyway) but I wonder if that was by design? I.e. that the old service graph doesn't get shut down on hot reload?

When trying to understand what's going on it seemed to me that an easy enough fix would be to add, say, shutdownServices() at this https://github.com/ratpack/ratpack/blob/31f7c63bcd360004121c9848a29c585612b62db9/ratpack-core/src/main/java/ratpack/server/internal/DefaultRatpackServer.java#L292 line; what do you think?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment