Skip to content

Instantly share code, notes, and snippets.

@SlyDen
Forked from ldaley/Example.java
Created April 8, 2016 08:01
Show Gist options
  • Save SlyDen/a339db7053b5008391d0aae98c297882 to your computer and use it in GitHub Desktop.
Save SlyDen/a339db7053b5008391d0aae98c297882 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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment