SpringBoot中如何定时任务,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。这篇文章将介绍怎么通过spring去做调度任务。构建工程创建一个Springbo
SpringBoot中如何定时任务,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
这篇文章将介绍怎么通过spring去做调度任务。
创建一个Springboot工程,在它的程序入口加上@EnableScheduling,开启调度任务。
@SpringBootApplication@EnableSchedulingpublic class SpringbootSchedulingTasksApplication { public static void main(String[] args) { SpringApplication.run(SpringbootSchedulingTasksApplication.class, args); }}
创建一个定时任务,每过5s在控制台打印当前时间。
@Componentpublic class ScheduledTasks { private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class); private static final SimpleDateFORMat dateFormat = new SimpleDateFormat("HH:mm:ss"); @Scheduled(fixedRate = 5000) public void reportCurrentTime() { log.info("The time is now {}", dateFormat.format(new Date())); }}
通过在方法上加@Scheduled注解,表明该方法是一个调度任务。
@Scheduled(fixedRate = 5000) :上一次开始执行时间点之后5秒再执行
@Scheduled(fixedDelay = 5000) :上一次执行完毕时间点之后5秒再执行
@Scheduled(initialDelay=1000, fixedRate=5000) :第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次
@Scheduled(cron=” /5 “) :通过cron表达式定义规则,什么是cro表达式,自行搜索引擎。
启动springboot工程,控制台没过5s就打印出了当前的时间。
2017-04-29 17:39:37.672 INFO 677 —- [pool-1-thread-1] com.forezp.task.ScheduledTasks : The time is now 17:39:37
2017-04-29 17:39:42.671 INFO 677 —- [pool-1-thread-1] com.forezp.task.ScheduledTasks : The time is now 17:39:42
2017-04-29 17:39:47.672 INFO 677 —- [pool-1-thread-1] com.forezp.task.ScheduledTasks : The time is now 17:39:47
2017-04-29 17:39:52.675 INFO 677 —- [pool-1-thread-1] com.forezp.task.ScheduledTasks : The time is now 17:39:52
在springboot创建定时任务比较简单,只需2步:
在程序的入口加上@EnableScheduling注解。
在定时方法上加@Scheduled注解。
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注编程网精选频道,感谢您对编程网的支持。
--结束END--
本文标题: SpringBoot中如何定时任务
本文链接: https://www.lsjlt.com/news/296013.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0