tags | projects | ||
---|---|---|---|
|
|
This guide walks you through the steps for scheduling tasks with Spring.
You’ll build an application that prints out the current time every five seconds using Spring’s @Scheduled
annotation.
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.
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]
@SpringBootApplication
is a convenience annotation that adds all of the following:
-
@Configuration
tags the class as a source of bean definitions for the application context. -
@EnableAutoConfiguration
tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings. Technically, Spring Boot doesn’t have anything to auto-configure when it comes to scheduling but a future version might. -
@ComponentScan
tells Spring to look for other components, configurations, and services in the thehello
package, allowing it to find theScheduledTasks
.
The main()
method uses Spring Boot’s SpringApplication.run()
method to launch an application. Did you notice that there wasn’t a single line of XML? This application is 100% pure Java and you didn’t have to deal with configuring any plumbing or infrastructure.
@EnableScheduling
ensures that a background task executor is created. Without it, nothing gets scheduled.
Logging output is displayed. You should see your scheduled task fire every 5 seconds:
[...] The time is now 13:10:00 The time is now 13:10:05 The time is now 13:10:10 The time is now 13:10:15
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.