spring boot 开启定时任务

spring boot 集成了许多注解,极大的方便了软件的开发,而@Scheduled注解则可以为我们开启定时任务。

demo 如下

@Configuration
@EnableScheduling // 2.开启定时任务
public class task(){
//采用cron表达式设置任务开启时间
@Scheduled(cron ="${cron}")
//@Scheduled(fixedRateString ="${system.wx.fixedRate}",initialDelayString = "${system.wx.initialDelay}")
public void a(){
system.out.print("执行任务时间"+new Date())

}
}
这里有一些注意点 如果
@Scheduled标注在方法上,这个方法必须是空参的,
//cron属性适合固定周期运作,如果你要两天执行一次任务就不太适合了,一个月的天数不是固定的,如果这天执行的是31号,那么下个月会从一号执行,而不是二号
//下面的fixedRate这个注解表示间隔多少毫秒执行,不会顾及执行时间,initialDelay是表示等待多久执行第一次方法
@Scheduled(fixedRateString ="${system.wx.fixedRate}",initialDelayString = "${system.wx.initialDelay}")
@Scheduled 里面属性的具体用法大家可以百度
建议写在配置文件里

posted @ 2021-11-10 11:31  才才的博客  阅读(476)  评论(0)    收藏  举报