Quarkus - Scheduling Periodic Tasks with Quartz

Modern applications often need to run specific tasks periodically. In this guide, you learn how to schedule periodic clustered tasks using the Quartz extension.

This technology is considered preview.

In preview, backward compatibility and presence in the ecosystem is not guaranteed. Specific improvements might require to change configuration or APIs and plans to become stable are under way. Feedback is welcome on our mailing list or as issues in our GitHub issue tracker.

For a full list of possible extension statuses, check our FAQ entry.

If you only need to run in-memory scheduler use the Scheduler 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+

  • Docker and Docker Compose installed on your machine

Architecture

In this guide, we are going to expose one Rest API tasks to visualise the list of tasks created by a Quartz job running every 10 seconds.

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 quartz-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=quartz-quickstart \
  4. -DclassName="org.acme.quartz.TaskResource" \
  5. -Dpath="/tasks" \
  6. -Dextensions="quartz, hibernate-orm-panache, flyway, resteasy-jsonb, jdbc-postgresql"
  7. cd quartz-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.quartz.TaskResource resource

  • an associated test

The Maven project also imports the Quarkus Quartz extension.

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

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

This will add the following to your pom.xml:

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

To use a JDBC store, the quarkus-agroal extension, which provides the datasource support, is also required.

Creating the Task Entity

In the org.acme.quartz package, create the Task class, with the following content:

  1. package org.acme.quartz;
  2. import javax.persistence.Entity;
  3. import java.time.Instant;
  4. import javax.persistence.Table;
  5. import io.quarkus.hibernate.orm.panache.PanacheEntity;
  6. @Entity
  7. @Table(name="TASKS")
  8. public class Task extends PanacheEntity { (1)
  9. public Instant createdAt;
  10. public Task() {
  11. createdAt = Instant.now();
  12. }
  13. public Task(Instant time) {
  14. this.createdAt = time;
  15. }
  16. }
  1. Declare the entity using Panache

Creating a scheduled job

In the org.acme.quartz package, create the TaskBean class, with the following content:

  1. package org.acme.quartz;
  2. import javax.enterprise.context.ApplicationScoped;
  3. import javax.transaction.Transactional;
  4. import io.quarkus.scheduler.Scheduled;
  5. @ApplicationScoped (1)
  6. public class TaskBean {
  7. @Transactional
  8. @Scheduled(every = "10s") (2)
  9. void schedule() {
  10. Task task = new Task(); (3)
  11. task.persist(); (4)
  12. }
  13. }
  1. Declare the bean in the application scope

  2. Use the @Scheduled annotation to instruct Quarkus to run this method every 10 seconds.

  3. Create a new Task with the current start time.

  4. Persist the task in database using Panache.

Scheduling Jobs Programmatically

It is also possible to leverage the Quartz API directly. You can inject the underlying org.quartz.Scheduler in any bean:

  1. package org.acme.quartz;
  2. @ApplicationScoped
  3. public class TaskBean {
  4. @Inject
  5. org.quartz.Scheduler quartz; (1)
  6. void onStart(@Observes StartupEvent event) {
  7. JobDetail job = JobBuilder.newJob(MyJob.class)
  8. .withIdentity("myJob", "myGroup")
  9. .build();
  10. Trigger trigger = TriggerBuilder.newTrigger()
  11. .withIdentity("myTrigger", "myGroup")
  12. .startNow()
  13. .withSchedule(
  14. SimpleScheduleBuilder.simpleSchedule()
  15. .withIntervalInSeconds(10)
  16. .repeatForever())
  17. .build();
  18. quartz.scheduleJob(job, trigger); (2)
  19. }
  20. @Transactional
  21. void performTask() {
  22. Task task = new Task();
  23. task.persist();
  24. }
  25. // A new instance of MyJob is created by Quartz for every job execution
  26. public static class MyJob implements Job {
  27. public void execute(JobExecutionContext context) throws JobExecutionException {
  28. Arc.container().instance(TaskBean.class).get(). performTask(); (3)
  29. }
  30. }
  31. }
  1. Inject the underlying org.quartz.Scheduler instance.

  2. Schedule a new job using the Quartz API.

  3. Lookup the bean instance of TaskBean and invoke the performTask() method from the job.

By default, the scheduler is not started unless a @Scheduled business method is found. You may need to force the start of the scheduler for “pure” programmatic scheduling. See also Quartz Configuration Reference.

Updating the application configuration file

Edit the application.properties file and add the below configuration:

  1. # Quartz configuration
  2. quarkus.quartz.clustered=true (1)
  3. quarkus.quartz.store-type=jdbc-cmt (2)
  4. # Datasource configuration.
  5. quarkus.datasource.db-kind=postgresql
  6. quarkus.datasource.username=quarkus_test
  7. quarkus.datasource.password=quarkus_test
  8. quarkus.datasource.jdbc.url=jdbc:postgresql://localhost/quarkus_test
  9. # Hibernate configuration
  10. quarkus.hibernate-orm.database.generation=none
  11. quarkus.hibernate-orm.log.sql=true
  12. quarkus.hibernate-orm.sql-load-script=no-file
  13. # flyway configuration
  14. quarkus.flyway.connect-retries=10
  15. quarkus.flyway.table=flyway_quarkus_history
  16. quarkus.flyway.migrate-at-start=true
  17. quarkus.flyway.baseline-on-migrate=true
  18. quarkus.flyway.baseline-version=1.0
  19. quarkus.flyway.baseline-description=Quartz
  1. Indicate that the scheduler will be run in clustered mode

  2. Use the database store to persist job related information so that they can be shared between nodes

Updating the resource and the test

Edit the TaskResource class, and update the content to:

  1. package org.acme.quartz;
  2. import java.util.List;
  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("/tasks")
  8. @Produces(MediaType.APPLICATION_JSON)
  9. public class TaskResource {
  10. @GET
  11. public List<Task> listAll() {
  12. return Task.listAll(); (1)
  13. }
  14. }
  1. Retrieve the list of created tasks from the database

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

  1. package org.acme.quartz;
  2. import io.quarkus.test.junit.QuarkusTest;
  3. import static org.hamcrest.Matchers.greaterThanOrEqualTo;
  4. import org.junit.jupiter.api.Test;
  5. import static io.restassured.RestAssured.given;
  6. import static org.hamcrest.CoreMatchers.is;
  7. @QuarkusTest
  8. public class TaskResourceTest {
  9. @Test
  10. public void tasks() throws InterruptedException {
  11. Thread.sleep(1000); // wait at least a second to have the first task created
  12. given()
  13. .when().get("/tasks")
  14. .then()
  15. .statusCode(200)
  16. .body("size()", is(greaterThanOrEqualTo(1))); (1)
  17. }
  18. }
  1. Ensure that we have a 200 response and at least one task created

Creating Quartz Tables

Add a SQL migration file named src/main/resources/db/migration/V2.0.0__QuarkusQuartzTasks.sql with the content copied from file with the content from V2.0.0__QuarkusQuartzTasks.sql.

Configuring the load balancer

In the root directory, create a nginx.conf file with the following content:

  1. user nginx;
  2. events {
  3. worker_connections 1000;
  4. }
  5. http {
  6. server {
  7. listen 8080;
  8. location / {
  9. proxy_pass http://tasks:8080; (1)
  10. }
  11. }
  12. }
  1. Route all traffic to our tasks application

Setting Application Deployment

In the root directory, create a docker-compose.yml file with the following content:

  1. version: '3'
  2. services:
  3. tasks: (1)
  4. image: quarkus-quickstarts/quartz:1.0
  5. build:
  6. context: ./
  7. dockerfile: src/main/docker/Dockerfile.${QUARKUS_MODE:-jvm}
  8. environment:
  9. QUARKUS_DATASOURCE_URL: jdbc:postgresql://postgres/quarkus_test
  10. networks:
  11. - tasks-network
  12. depends_on:
  13. - postgres
  14. nginx: (2)
  15. image: nginx:1.17.6
  16. volumes:
  17. - ./nginx.conf:/etc/nginx/nginx.conf:ro
  18. depends_on:
  19. - tasks
  20. ports:
  21. - 8080:8080
  22. networks:
  23. - tasks-network
  24. postgres: (3)
  25. image: postgres:11.3
  26. container_name: quarkus_test
  27. environment:
  28. - POSTGRES_USER=quarkus_test
  29. - POSTGRES_PASSWORD=quarkus_test
  30. - POSTGRES_DB=quarkus_test
  31. ports:
  32. - 5432:5432
  33. networks:
  34. - tasks-network
  35. networks:
  36. tasks-network:
  37. driver: bridge
  1. Define the tasks service

  2. Define the nginx load balancer to route incoming traffic to an appropriate node

  3. Define the configuration to run the database

Running the database

In a separate terminal, run the below command:

  1. docker-compose up postgres (1)
  1. Start the database instance using the configuration options supplied in the docker-compose.yml file

Run the application in Dev Mode

Run the application with: ./mvnw quarkus:dev. After a few seconds, open another terminal and run curl localhost:8080/tasks to verify that we have at least one task created.

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.

Packaging the application and run several instances

The application can be packaged using ./mvnw clean package. Once the build is successful, run the below command:

  1. docker-compose up --scale tasks=2 --scale nginx=1 (1)
  1. Start two instances of the application and a load balancer

After a few seconds, in another terminal, run curl localhost:8080/tasks to verify that tasks were only created at different instants and in an interval of 10 seconds.

You can also generate the native executable with ./mvnw clean package -Pnative.

Registering Plugin and Listeners

You can register a plugin, jobListener or triggerListener through Quarkus configuration.

The example bellow registers the plugin org.quartz.plugins.history.LoggingJobHistoryPlugin named as jobHistory with the property jobSuccessMessage defined as Job [{1}.{0}] execution complete and reports: {8}

  1. quarkus.quartz.plugin.jobHistory.class=org.quartz.plugins.history.LoggingJobHistoryPlugin
  2. quarkus.quartz.plugin.jobHistory.jobSuccessMessage=Job [{1}.{0}] execution complete and reports: {8}

You can also register a listener programmatically with an injected org.quartz.Scheduler

  1. public class MyListenerManager {
  2. void onStart(@Observes StartupEvent event, org.quartz.Scheduler scheduler) throws SchedulerException {
  3. scheduler.getListenerManager().addJobListener(new MyJogListener());
  4. scheduler.getListenerManager().addTriggerListener(new MyTriggerListener());
  5. }
  6. }

Quartz Configuration Reference