Skip to content

Instantly share code, notes, and snippets.

@ldaley
Created April 8, 2016 00:11
Show Gist options
  • Select an option

  • Save ldaley/a3e3253e9b7b0a4ccae466eecb0ca0dd to your computer and use it in GitHub Desktop.

Select an option

Save ldaley/a3e3253e9b7b0a4ccae466eecb0ca0dd to your computer and use it in GitHub Desktop.

Revisions

  1. ldaley created this gist Apr 8, 2016.
    68 changes: 68 additions & 0 deletions Example.java
    Original 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();
    }
    }