-
-
Save shanmuha/fbd5bff896e0bd045b277682d1d4887a to your computer and use it in GitHub Desktop.
Periodic background jobs in Ratpack
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 characters
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