在 Spring Boot 中创建一个定时任务,可以通过以下步骤实现:
- 添加依赖:确保你的
pom.xml
中包含了spring-boot-starter
依赖。 - 启用定时任务:在主应用程序类上添加
@EnableScheduling
注解。 - 创建定时任务类:使用
@Scheduled
注解定义任务方法。
以下是一个简单的示例:
在这个示例中,ScheduledTasks
类中的 performTask
方法会每5秒执行一次。
在 Spring Boot 中使用 Cron 表达式定义定时任务,可以通过 @Scheduled
注解的 cron
属性来实现。以下是一个示例:
在这个示例中,@Scheduled(cron = "0 0 12 * * ?")
配置的 Cron 表达式会使 performTask
方法每天中午12点执行一次。