Monitoring Spring @Scheduled tasks
Spring's @Scheduled is convenient and silent. The default scheduler has a single thread, so one stuck
task blocks every other scheduled task in the app, and nothing reports it.
Ping when the task finishes
@Scheduled(cron = "0 0 3 * * *", zone = "UTC")
public void nightlyExport() {
try {
exportService.run();
heartbeat("");
} catch (Exception e) {
heartbeat("/fail");
throw e;
}
}
private void heartbeat(String suffix) {
try {
HttpClient.newHttpClient().send(
HttpRequest.newBuilder(URI.create("https://cronpup.com/p/YOUR-UUID" + suffix))
.timeout(Duration.ofSeconds(10)).build(),
HttpResponse.BodyHandlers.discarding());
} catch (Exception ignored) { /* never fail the job because the ping failed */ }
}
Note that Spring cron expressions have six fields (seconds first). The monitor uses the usual five:
0 3 * * * in UTC.
Catch hung tasks
Send /start when the task begins. If the finish ping doesn't follow within the grace period, you get a
"started but didn't finish" alert, which is the stuck-thread-pool case. Try it free.