Java / Maven

Schedule periodic tasks inside your Micronaut applications

Learn how to schedule periodic tasks inside your Micronaut microservices.

Sergio del Amo
On this guide
In this section

Getting Started

In this guide, we will create a Micronaut application written in Java.

Nowadays it is pretty usual to have some kind of cron or scheduled task that needs to run every midnight, every hour, a few times a week,…​

In this guide you will learn how to use Micronaut capabilities to schedule periodic tasks inside a Micronaut microservice.

What you will need

To complete this guide, you will need the following:

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.

Writing the Application

Create an application using the Micronaut Command Line Interface or with Micronaut Launch.

mn create-app example.micronaut.micronautguide --build=maven --lang=java
Note
If you don’t specify the --build argument, Gradle with the Kotlin DSL is used as the build tool.
If you don’t specify the --lang argument, Java is used as the language.
If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.

The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.

Set log level INFO for package demo

In this guide, we will use several log statements to show Job execution.

Add this statement to the end of logback.xml:

java/src/main/resources/logback.xml
<logger name="example.micronaut" level="INFO"/>

The above line configures a logger for package example.micronaut with log level INFO.

Creating a Job

Create the HelloWorldJob class:

java/src/main/java/example/micronaut/HelloWorldJob.java

Now start the application. Execute the ./mvnw mn:run command, which will start the application on port 8080.

After a few seconds, you will see the following output:

Business logic in dedicated Use Cases

Although the previous example is valid, usually you don’t want to put your business logic in a Job. A better approach is to create an additional bean that the Job invokes. This approach decouples your business logic from the scheduling logic. Moreover, it facilitates testing and maintenance. Let’s see an example:

Create the following use case:

java/src/main/java/example/micronaut/EmailUseCase.java
package example.micronaut;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jakarta.inject.Singleton;
import java.text.SimpleDateFormat;
import java.util.Date;

@Singleton
public class EmailUseCase {
    private static final Logger LOG = LoggerFactory.getLogger(EmailUseCase.class);

    void send(String user, String message) {
        LOG.info("Sending email to {}: {} at {}", user, message, new SimpleDateFormat("dd/M/yyyy hh:mm:ss").format(new Date()));
    }
}

And then the Job:

java/src/main/java/example/micronaut/DailyEmailJob.java

Scheduling a Job Manually

Consider the following scenario. You want to send every user an email two hours after they register on your application and ask them about their experiences during this first interaction.

For this guide, we will schedule a Job to trigger after one minute.

To test it, we will call a new use case named RegisterUseCase twice when the application starts.

Modify Application.java:

java/src/main/java/example/micronaut/Application.java

Create a runnable task EmailTask.java

java/src/main/java/example/micronaut/EmailTask.java
package example.micronaut;

public class EmailTask implements Runnable {

    private String email;
    private String message;
    private EmailUseCase emailUseCase;

    public EmailTask(EmailUseCase emailUseCase, String email, String message) {
        this.email = email;
        this.message = message;
        this.emailUseCase = emailUseCase;
    }

    @Override
    public void run() {
        emailUseCase.send(email, message);
    }

}

Create RegisterUseCase.java, which schedules the previous task.

java/src/main/java/example/micronaut/RegisterUseCase.java

If you execute the above code, you will see the Job being executed one minute after we schedule it and with the supplied email address.

INFO  example.micronaut.RegisterUseCase - saving harry@micronaut.example at 15/5/2018 06:25:14
INFO  example.micronaut.RegisterUseCase - saving ron@micronaut.example at 15/5/2018 06:25:34
INFO  example.micronaut.EmailUseCase - Sending email to harry@micronaut.example : Welcome to Micronaut at 15/5/2018 06:26:14
INFO  example.micronaut.EmailUseCase - Sending email to ron@micronaut.example : Welcome to the Micronaut framework at 15/5/2018 06:26:34

Summary

During this guide, we learned how to configure Jobs using the @Scheduled annotation using fixedDelay, initialDelay, and cron, as well as manually configuring Jobs with a TaskScheduler and tasks.

Generate a Micronaut Application Native Executable with GraalVM

We will use GraalVM, an advanced JDK with ahead-of-time Native Image compilation, to generate a native executable of this Micronaut application.

Compiling Micronaut applications ahead of time with GraalVM significantly improves startup time and reduces the memory footprint of JVM-based applications.

Note
Only Java and Kotlin projects support using GraalVM’s native-image tool. Groovy relies heavily on reflection, which is only partially supported by GraalVM.

GraalVM Installation

The easiest way to install GraalVM on Linux or Mac is to use SDKMan.io.

Java 25
sdk install java 25.0.2-graal

For installation on Windows, or for a manual installation on Linux or Mac, see the GraalVM Getting Started documentation.

The previous command installs Oracle GraalVM, which is free to use in production and free to redistribute, at no cost, under the GraalVM Free Terms and Conditions.

Alternatively, you can use the GraalVM Community Edition:

Java 25
sdk install java 25.0.2-graalce

Native Executable Generation

To generate a native executable using Maven, run:

./mvnw package -Dpackaging=native-image

The native executable is created in the target directory and can be run with target/micronautguide.

It is possible to customize the name of the native executable or pass additional build arguments using the Maven plugin for GraalVM Native Image building. Declare the plugin as follows:

pom.xml

Execute the native executable, and you will see the log message of the Jobs appear:

10:16:20.803 [pool-2-thread-1] INFO  example.micronaut.HelloWorldJob - Simple Job every 10 seconds: 09/12/2019 10:16:20
10:16:20.806 [main] INFO  example.micronaut.RegisterUseCase - saving harry@micronaut.example at 09/12/2019 10:16:20
10:16:25.804 [pool-2-thread-2] INFO  example.micronaut.HelloWorldJob - Simple Job every 45 seconds: 09/12/2019 10:16:25
10:16:30.807 [pool-2-thread-4] INFO  example.micronaut.HelloWorldJob - Simple Job every 10 seconds: 09/12/2019 10:16:30

Next Steps

Explore more features with Micronaut Guides.

Help with the Micronaut Framework

The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.

License

Note
All guides are released with an Apache License 2.0 for the code and a Creative Commons Attribution 4.0 license for the writing and media (images).