Quarkus - Scheduling Periodic Tasks

Modern applications often need to run specific tasks periodically. In this guide, you learn how to schedule periodic tasks.

If you need a clustered scheduler use the Quartz extension.

Prerequisites

To complete this guide, you need:

  • less than 10 minutes

  • an IDE

  • JDK 1.8+ installed with JAVA_HOME configured appropriately

  • Apache Maven 3.6.2+

Architecture

In this guide, we create a straightforward application accessible using HTTP to get the current value of a counter. This counter is periodically (every 10 seconds) incremented.

Architecture

Solution

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.

Clone the Git repository: git clone [https://github.com/quarkusio/quarkus-quickstarts.git](https://github.com/quarkusio/quarkus-quickstarts.git), or download an archive.

The solution is located in the scheduler-quickstart directory.

Creating the Maven project

First, we need a new project. Create a new project with the following command:

  1. mvn io.quarkus:quarkus-maven-plugin:1.7.6.Final:create \
  2. -DprojectGroupId=org.acme \
  3. -DprojectArtifactId=scheduler-quickstart \
  4. -DclassName="org.acme.scheduler.CountResource" \
  5. -Dpath="/count" \
  6. -Dextensions="scheduler"
  7. cd scheduler-quickstart

It generates:

  • the Maven structure

  • a landing page accessible on [http://localhost:8080](http://localhost:8080)

  • example Dockerfile files for both native and jvm modes

  • the application configuration file

  • an org.acme.scheduler.CountResource resource

  • an associated test

The Maven project also imports the Quarkus scheduler extension.

If you already have your Quarkus project configured, you can add the scheduler extension to your project by running the following command in your project base directory:

  1. ./mvnw quarkus:add-extension -Dextensions="scheduler"

This will add the following to your pom.xml:

  1. <dependency>
  2. <groupId>io.quarkus</groupId>
  3. <artifactId>quarkus-scheduler</artifactId>
  4. </dependency>

Creating a scheduled job

In the org.acme.scheduler package, create the CounterBean class, with the following content:

  1. package org.acme.scheduler;
  2. import java.util.concurrent.atomic.AtomicInteger;
  3. import javax.enterprise.context.ApplicationScoped;
  4. import io.quarkus.scheduler.Scheduled;
  5. import io.quarkus.scheduler.ScheduledExecution;
  6. @ApplicationScoped (1)
  7. public class CounterBean {
  8. private AtomicInteger counter = new AtomicInteger();
  9. public int get() { (2)
  10. return counter.get();
  11. }
  12. @Scheduled(every="10s") (3)
  13. void increment() {
  14. counter.incrementAndGet(); (4)
  15. }
  16. @Scheduled(cron="0 15 10 * * ?") (5)
  17. void cronJob(ScheduledExecution execution) {
  18. counter.incrementAndGet();
  19. System.out.println(execution.getScheduledFireTime());
  20. }
  21. @Scheduled(cron = "{cron.expr}") (6)
  22. void cronJobWithExpressionInConfig() {
  23. counter.incrementAndGet();
  24. System.out.println("Cron expression configured in application.properties");
  25. }
  26. }
  1. Declare the bean in the application scope

  2. The get() method allows retrieving the current value.

  3. Use the @Scheduled annotation to instruct Quarkus to run this method every 10 seconds provided a worker thread is available (Quarkus is using 10 worker threads for the scheduler). If it is not available the method invocation should be re-scheduled by default i.e it should be invoked as soon as possible. The invocation of the scheduled method does not depend on the status or result of the previous invocation.

  4. The code is pretty straightforward. Every 10 seconds, the counter is incremented.

  5. Define a job with a cron-like expression. The annotated method is executed at 10:15am every day.

  6. Define a job with a cron-like expression cron.expr which is configurable in application.properties.

Updating the application configuration file

Edit the application.properties file and add the cron.expr configuration:

  1. # By default, the syntax used for cron expressions is based on Quartz - http://www.quartz-scheduler.org/documentation/quartz-2.3.0/tutorials/crontrigger.html
  2. # You can change the syntax using the following property:
  3. # quarkus.scheduler.cron-type=unix
  4. cron.expr=*/5 * * * * ?

Updating the resource and the test

Edit the CountResource class, and update the content to:

  1. package org.acme.scheduler;
  2. import javax.inject.Inject;
  3. import javax.ws.rs.GET;
  4. import javax.ws.rs.Path;
  5. import javax.ws.rs.Produces;
  6. import javax.ws.rs.core.MediaType;
  7. @Path("/count")
  8. public class CountResource {
  9. @Inject
  10. CounterBean counter; (1)
  11. @GET
  12. @Produces(MediaType.TEXT_PLAIN)
  13. public String hello() {
  14. return "count: " + counter.get(); (2)
  15. }
  16. }
  1. Inject the CounterBean

  2. Send back the current counter value

We also need to update the tests. Edit the CountResourceTest class to match:

  1. package org.acme.scheduler;
  2. import io.quarkus.test.junit.QuarkusTest;
  3. import org.junit.jupiter.api.Test;
  4. import static io.restassured.RestAssured.given;
  5. import static org.hamcrest.CoreMatchers.containsString;
  6. @QuarkusTest
  7. public class CountResourceTest {
  8. @Test
  9. public void testHelloEndpoint() {
  10. given()
  11. .when().get("/count")
  12. .then()
  13. .statusCode(200)
  14. .body(containsString("count")); (1)
  15. }
  16. }
  1. Ensure that the response contains count

Package and run the application

Run the application with: ./mvnw compile quarkus:dev. In another terminal, run curl localhost:8080/count to check the counter value. After a few seconds, re-run curl localhost:8080/count to verify the counter has been incremented.

Observe the console to verify that the message Cron expression configured in application.properties has been displayed indicating that the cron job using an expression configured in application.properties has been triggered.

As usual, the application can be packaged using ./mvnw clean package and executed using the -runner.jar file. You can also generate the native executable with ./mvnw clean package -Pnative.

Scheduler Configuration Reference