How to create a scheduled method with spring boot

Posted by Java developer blog on August 9, 2020

Overview

Sometimes you need to create a method that will be called many times in the future. We usually call such a method as a scheduled method. In the post, we are going to discuss how to create a scheduled method with spring boot.

Scheduled method

Firstly, add @EnableScheduling to any @Configuration class to enable scheduling in the application. I recommend adding it to the class marked with @SpringBootApplication.

1
2
3
4
5
6
7
8
9
10
11
12
13
package org.maks.scheduledmethodexample

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.scheduling.annotation.EnableScheduling

@EnableScheduling
@SpringBootApplication
class ScheduledMethodExampleApplication

fun main(args: Array<String>) {
	runApplication<ScheduledMethodExampleApplication>(*args)
}

Secondly, implement a method. Then add @Scheduled(fixedRateString = “…”) or @Scheduled(cron = “…”) annotation to the method. The former allows you to execute the method at a fixed interval while the latter helps to set custom time intervals with the help of Cron expressions. You could use Cron Expression Generator to generate proper Cron expression.

1
2
3
4
5
6
7
8
9
10
11
12
13
package org.maks.scheduledmethodexample

import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Service

@Service
class ScheduledService {

    @Scheduled(fixedRate = 1000)
    fun run() {
        println("run() has been executed")
    }
}

You could even combine several @Scheduled with the help of @Schedules annotation.

Conclusion

We have discussed how to create a scheduled method with spring boot. You could check out the source code here.