/gs-scheduling-tasks

Scheduling Tasks :: Learn how to schedule tasks with Spring.

Primary LanguageShell

tags projects
scheduling
spring-framework

This guide walks you through the steps for scheduling tasks with Spring.

What you’ll build

You’ll build an application that prints out the current time every five seconds using Spring’s @Scheduled annotation.

What you’ll need

Create a scheduled task

Now that you’ve set up your project, you can create a scheduled task.

src/main/java/hello/ScheduledTasks.java

link:complete/src/main/java/hello/ScheduledTasks.java[role=include]

The Scheduled annotation defines when a particular method runs. NOTE: This example uses fixedRate, which specifies the interval between method invocations measured from the start time of each invocation. There are other options, like fixedDelay, which specifies the interval between invocations measured from the completion of the task. You can also use @Scheduled(cron=". . .") expressions for more sophisticated task scheduling.

Enable Scheduling

Although scheduled tasks can be embedded in web apps and WAR files, the simpler approach demonstrated below creates a standalone application. You package everything in a single, executable JAR file, driven by a good old Java main() method.

src/main/java/hello/Application.java

link:complete/src/main/java/hello/Application.java[role=include]

@EnableScheduling ensures that a background task executor is created. Without it, nothing gets scheduled.

Logging output is displayed and you can see from the logs that it is on a background thread. You should see your scheduled task fire every 5 seconds:

[...]
2016-08-25 13:10:00.143  INFO 31565 --- [pool-1-thread-1] hello.ScheduledTasks : The time is now 13:10:00
2016-08-25 13:10:05.143  INFO 31565 --- [pool-1-thread-1] hello.ScheduledTasks : The time is now 13:10:05
2016-08-25 13:10:10.143  INFO 31565 --- [pool-1-thread-1] hello.ScheduledTasks : The time is now 13:10:10
2016-08-25 13:10:15.143  INFO 31565 --- [pool-1-thread-1] hello.ScheduledTasks : The time is now 13:10:15

Summary

Congratulations! You created an application with a scheduled task. Heck, the actual code was shorter than the build file! This technique works in any type of application.