Spring Boot — How to Schedule Tasks | Code Factory

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>spring-boot-scheduler-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-scheduler-demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package com.example;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class SpringBootSchedulerDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootSchedulerDemoApplication.class, args);
}
}
package com.example.schedule;import java.time.format.DateTimeFormatter;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class ScheduledTasks {
private static final Logger logger = LoggerFactory.getLogger(ScheduledTasks.class);
private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
public void scheduleTaskWithFixedRate() {} public void scheduleTaskWithFixedDelay() {} public void scheduleTaskWithInitialDelay() {} public void scheduleTaskWithCronExpression() {}
}
  • The method should have a void return type.
  • The method should not accept any arguments.

1. Scheduling a Task with Fixed Rate

@Scheduled(fixedRate = 2000)
public void scheduleTaskWithFixedRate() {
logger.info("Fixed Rate Schedule : " + dateTimeFormatter.format(LocalDateTime.now()));
}
Fixed Rate Schedule : 14:33:40
Fixed Rate Schedule : 14:33:42
Fixed Rate Schedule : 14:33:44
Fixed Rate Schedule : 14:33:46
...
...

2. Scheduling a Task with Fixed Delay

@Scheduled(fixedDelay = 2000)
public void scheduleTaskWithFixedDelay() {
logger.info("Fixed Delay Schedule : " + dateTimeFormatter.format(LocalDateTime.now()));
try {
TimeUnit.SECONDS.sleep(5);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
Fixed Delay Schedule : 14:35:58
Fixed Delay Schedule : 14:36:05
Fixed Delay Schedule : 14:36:12
Fixed Delay Schedule : 14:36:19
...
...

3. Scheduling a Task With Fixed Rate and Initial Delay

@Scheduled(fixedRate = 2000, initialDelay = 5000)
public void scheduleTaskWithInitialDelay() {
logger.info("Fixed Rate Task with Initial Delay Schedule : " + dateTimeFormatter.format(LocalDateTime.now()));
}
Fixed Rate Task with Initial Delay Schedule : 14:39:10
Fixed Rate Task with Initial Delay Schedule : 14:39:12
Fixed Rate Task with Initial Delay Schedule : 14:39:14
Fixed Rate Task with Initial Delay Schedule : 14:39:16
...
...

4. Scheduling a Task using Cron Expression

@Scheduled(cron = "0 * * * * ?")
public void scheduleTaskWithCronExpression() {
logger.info("Cron task Schedule : " + dateTimeFormatter.format(LocalDateTime.now()));
}
Cron task Schedule : 14:42:00
Cron task Schedule : 14:43:00
Cron task Schedule : 14:44:00
...
...

Running @Scheduled Tasks in a Custom Thread Pool

logger.info("Current Thread : {}", Thread.currentThread().getName());
Current Thread : scheduling-1
package com.example.config;import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
@Configuration
public class SchedulerConfig implements SchedulingConfigurer {
private final int POOL_SIZE = 10;
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(POOL_SIZE);
threadPoolTaskScheduler.setThreadNamePrefix("my-scheduled-task-pool-");
threadPoolTaskScheduler.initialize();
scheduledTaskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
}
}
Current Thread : my-scheduled-task-pool-2
Current Thread : my-scheduled-task-pool-1
Current Thread : my-scheduled-task-pool-4
...
Current Thread : my-scheduled-task-pool-1
Fixed Rate Task with Initial Delay Schedule : 14:50:52
Current Thread : my-scheduled-task-pool-4
Fixed Rate Schedule : 14:50:53
Current Thread : my-scheduled-task-pool-3
Fixed Rate Task with Initial Delay Schedule : 14:50:54
Current Thread : my-scheduled-task-pool-6
Fixed Rate Schedule : 14:50:55
Current Thread : my-scheduled-task-pool-7
Fixed Rate Task with Initial Delay Schedule : 14:50:56
Current Thread : my-scheduled-task-pool-2
Fixed Rate Schedule : 14:50:57
Current Thread : my-scheduled-task-pool-5
Fixed Rate Task with Initial Delay Schedule : 14:50:58
Current Thread : my-scheduled-task-pool-9
Fixed Delay Schedule : 14:50:58
Current Thread : my-scheduled-task-pool-8
Fixed Rate Schedule : 14:50:59
Current Thread : my-scheduled-task-pool-10
Cron task Schedule : 14:51:00
Current Thread : my-scheduled-task-pool-4
Fixed Rate Task with Initial Delay Schedule : 14:51:00
Current Thread : my-scheduled-task-pool-3
Fixed Rate Schedule : 14:51:01
Current Thread : my-scheduled-task-pool-6
Fixed Rate Task with Initial Delay Schedule : 14:51:02
Current Thread : my-scheduled-task-pool-7
Fixed Rate Schedule : 14:51:03
Current Thread : my-scheduled-task-pool-2
Fixed Rate Task with Initial Delay Schedule : 14:51:04
Current Thread : my-scheduled-task-pool-1
Fixed Rate Schedule : 14:51:05
Current Thread : my-scheduled-task-pool-5
Fixed Delay Schedule : 14:51:05
Current Thread : my-scheduled-task-pool-9
Fixed Rate Task with Initial Delay Schedule : 14:51:06
Current Thread : my-scheduled-task-pool-10
...
...

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Getting Started with RUST and VSCODE

Inside Codeland — the most inclusive developer conference yet

Embracing Functional Programming in Ruby

Distributed Architecture

Weather, But Then Make It LCD

Dependency Injection on iOS — part 4/4

[NSUserDefaults synchronize] is Planned to be Deprecated

Using The ‘Faker’ Ruby Gem

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Code Factory

Code Factory

More from Medium

Communication Between Microservices | Spring WebClient

Spring boot

Spring Cloud Gateway Authentication with Auth0