Created
April 8, 2016 00:11
-
-
Save ldaley/a3e3253e9b7b0a4ccae466eecb0ca0dd to your computer and use it in GitHub Desktop.
Revisions
-
ldaley created this gist
Apr 8, 2016 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,68 @@ 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(); } }