Micronaut scheduled tasks with @Scheduled

Micronaut provides powerful support for task scheduling using the @Scheduled annotation. Whether it’s sending emails, clearing temporary files, or syncing data, scheduled tasks can be a game-changer for automating backend operations.

This guide explains how to create scheduled tasks in Micronaut using Maven, with clean examples and explanations that even beginners can follow.

Micronaut scheduled tasks with @Scheduled

πŸ“¦ Project Setup

Use the Micronaut Launch tool or manually configure your project.

pom.xml (important dependencies)

Make sure to have a JDK version 17 or later and enable annotation processing in your IDE (e.g., IntelliJ, Eclipse).

🧠 What is @Scheduled?

The @Scheduled annotation allows you to declare tasks that run automatically based on a fixed delay, fixed rate, or a cron expression.

You can annotate methods in singleton beans, and Micronaut will invoke them according to the schedule.

πŸ”§ Configuration

Make sure the scheduling feature is enabled. In most setups, this is enabled by default.

You can explicitly enable it in application.yml:

No special scheduler config is needed unless you are tweaking advanced thread pool settings.

βœ… Example 1: Fixed Delay Execution

This method runs 10 seconds after the previous execution ends.

βœ… Example 2: Fixed Rate Execution

This task runs every 5 seconds, regardless of the duration of the previous task execution.

βœ… Example 3: Cron Expression

You can use standard UNIX cron expressions for precise scheduling control.

πŸ›‘ Error Handling in Scheduled Tasks

If an exception occurs inside a scheduled task, it will be logged by Micronaut, but won’t stop future executions.

You can add try-catch blocks to ensure graceful recovery:

πŸš€ Testing the Scheduler

Run your application using:

Watch the logs in the console. You’ll see timestamps every time a scheduled method executes.

🧰 Tips for Real-World Usage

  • Keep long-running tasks async or in separate threads to avoid blocking.
  • Use cron expressions for complex schedules (e.g., every Monday at 9 AM).
  • Schedule tasks based on environment profiles (e.g., only in production).
  • Use @Scheduled(initialDelay = "5s", fixedRate = "30s") for a delayed start.

πŸ“Š Monitoring Scheduled Tasks

Micronaut doesn’t provide out-of-the-box visibility into scheduled task metrics, but you can use Micrometer to monitor method invocation counts, timings, etc.

🏁 Conclusion

Scheduling background tasks is essential for most backend services. Micronaut makes this incredibly easy and expressive using just the @Scheduled annotation. From cron expressions to fixed-rate execution, you can automate tasks efficiently without external schedulers.

Start small with simple tasks, and grow into advanced scheduling scenarios using Micronaut’s powerful features.