
Understanding @Scheduled in Spring Boot with Kotlin
Discover how to implement scheduled tasks in your Kotlin Spring Boot application using the @Scheduled annotation. Learn about fixed rate execution, fixed delay patterns, cron expressions, and best practices for production environments
Spring Boot's @Scheduled
annotation provides a simple yet powerful way to execute tasks at fixed intervals or at specific times. In this guide, we'll explore how to implement scheduled tasks in your Kotlin Spring Boot application.
Key Takeaways
- Learn how to configure and use the
@Scheduled
annotation - Understand different scheduling patterns (fixed rate, fixed delay, cron expressions)
- Implement practical examples using Kotlin
- Best practices for scheduled tasks in production environments
Enabling Scheduled Tasks
First, enable scheduling in your Spring Boot application by adding the @EnableScheduling
annotation to your main application class:
@SpringBootApplication
@EnableScheduling
class MyApplication
fun main(args: Array<String>) {
runApplication<MyApplication>(*args)
}
Basic Usage
Let's look at different ways to schedule tasks:
Fixed Rate Execution
Execute a task at a fixed interval, regardless of the previous execution's completion:
@Component
class ScheduledTasks {
private val logger = LoggerFactory.getLogger(javaClass)
@Scheduled(fixedRate = 60000) // executes every minute
fun reportCurrentTime() {
logger.info("Current time is: ${LocalDateTime.now()}")
}
}
Fixed Delay Execution
Execute a task with a fixed delay between the completion of the previous execution and the start of the next:
@Component
class ScheduledTasks {
@Scheduled(fixedDelay = 30000) // 30 seconds delay after previous completion
fun processQueue() {
// Process items in queue
Thread.sleep(2000) // Simulate processing time
println("Queue processed at ${LocalDateTime.now()}")
}
}
Using Cron Expressions
Execute tasks using cron expressions for more complex scheduling patterns:
@Component
class ScheduledTasks {
@Scheduled(cron = "0 0 9 * * MON-FRI") // 9:00 AM on weekdays
fun dailyReport() {
println("Generating daily report...")
}
}
Best Practices
- Error Handling: Always implement proper error handling in scheduled tasks:
@Component
class ScheduledTasks {
private val logger = LoggerFactory.getLogger(javaClass)
@Scheduled(fixedRate = 60000)
fun processData() {
try {
// Your task logic here
} catch (e: Exception) {
logger.error("Error in scheduled task: ${e.message}", e)
}
}
}
- Configuration Properties: Use configuration properties for scheduling values:
@Configuration
@ConfigurationProperties(prefix = "app.scheduling")
class SchedulingProperties {
var reportInterval: Long = 60000 // default value
}
@Component
class ScheduledTasks(
private val props: SchedulingProperties
) {
@Scheduled(fixedRateString = "#{@schedulingProperties.reportInterval}")
fun generateReport() {
// Report generation logic
}
}
Common Cron Expression Examples
Here are some commonly used cron expressions:
- Every day at midnight:
0 0 0 * * ?
- Every weekday at 9:00 AM:
0 0 9 * * MON-FRI
- Every hour:
0 0 * * * ?
- Every 15 minutes:
0 */15 * * * ?
Conclusion
The @Scheduled
annotation in Spring Boot provides a flexible way to implement scheduled tasks in your application. Remember to choose the appropriate scheduling strategy based on your requirements, implement proper error handling, and use configuration properties for better maintainability.
For production environments, consider using a proper monitoring solution to track the execution of your scheduled tasks and ensure they're running as expected.