- Scheduling tasks with Spring
- App that prints current time every 5 seconds using
@Scheduled
- No dependencies
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>3.1.2</version> <!-- latest version doesn't work for this tutorial -->
<scope>test</scope>
</dependency>
-
ScheduledTasks
@Component public class ScheduledTasks { private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class); private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); @Scheduled(fixedRate = 5000) public void reportCurrentTime() { log.info("The time is now {}", dateFormat.format(new Date())); } }
Scheduled
- annotation- It defines when a particular method runs
fixedRate
- interval between method invocations (from start time of each invocation)- Other options
fixedDelay
- interval from completion of the task
@Scheduled(cron="...")
- for more sophistication
- Other options
-
Main class:
@SpringBootApplication @EnableScheduling // **(M)** public class SchedulingTasksApplication { public static void main(String[] args) { SpringApplication.run(SchedulingTasksApplication.class); } }
@EnableScheduling
- Ensures that a background task executor is created (required for scheduling)