Spring Boot @Scheduled cron 定时任务程序启动时执行一次

Spring Boot cron About 448 words

需求

每次凌晨执行一次的cron的定时任务,但需要在程序启动时先执行一次。

如:博客中的一个需求,获取《历史上的今天》文章列表。

代码

实现Spring中提供的InitializingBean接口,在afterPropertiesSet方法中调用定时任务的方法。

@Scheduled(cron = "0 0 0 * * ?")

@Component
public class Statistics implements InitializingBean {

    @Scheduled(cron = "0 0 0 * * ?")
    public void todayOnHistory() {
        getTodayOnHistoryPosts();
        // TODO
    }

    @Override
    public void afterPropertiesSet() {
        todayOnHistory();
    }

}
Views: 315 · Posted: 2024-05-28

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓
Today On History
Browsing Refresh