Groovy / 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 Groovy.

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=groovy
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:

groovy/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:

groovy/src/main/groovy/example/micronaut/HelloWorldJob.groovy

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:

groovy/src/main/groovy/example/micronaut/EmailUseCase.groovy
package example.micronaut

import groovy.transform.CompileStatic
import groovy.util.logging.Slf4j

import jakarta.inject.Singleton
import java.text.SimpleDateFormat

@Slf4j
@CompileStatic
@Singleton
class EmailUseCase {

    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:

groovy/src/main/groovy/example/micronaut/DailyEmailJob.groovy

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.groovy:

groovy/src/main/groovy/example/micronaut/Application.groovy

Create a runnable task EmailTask.groovy

groovy/src/main/groovy/example/micronaut/EmailTask.groovy
package example.micronaut

import groovy.transform.CompileStatic

@CompileStatic
class EmailTask implements Runnable {

    String email
    String message
    EmailUseCase emailUseCase

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

Create RegisterUseCase.groovy, which schedules the previous task.

groovy/src/main/groovy/example/micronaut/RegisterUseCase.groovy

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.

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).