springboot定时器

来源:互联网 发布:周易取名软件破解版 编辑:程序博客网 时间:2024/06/13 22:34

在使用spring的时候遇到如下场景:由于业务需要,需要定时更新数据库,比如每隔两个小时更新一次某个字段的状态,无论是什么场景只要是需要定时去执行某种操作都可以使用spring的定时器任务来解决,以下将介绍springboot如何使用定时器任务:

创建定时任务:

@Componentpublic class NoticeTask {    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");    /**     * 每两个小时更新一次过期停水通知状态     * @return     */    @Scheduled(fixedRate = 2*60*60*1000)    public void refreshNoticeStatus(){        System.out.println(simpleDateFormat.format(new Date()));    }}

以上代码中@Component将该类交给spring托管,通过使用@Scheduled注解就定义了一个定时器任务,该任务的执行周期为2小时,spring每两小时会调用一次该方法,fixedRate的单位是毫秒,表示任务执行的周期@Scheduled 还有其他一些用法如@Scheduled(initialDelay=5000, fixedRate=5000)延迟5秒之后每隔5秒执行一次(注意:springboot框架在启动的时候会直接执行一次定时任务,使用该方法可以避免该情况)

启用定时任务

@SpringBootApplication@EnableSchedulingpublic class ApplicationStart {    public static void main(String[] args) {        SpringApplication.run(ApplicationStart.class, args);    }}

通过在springboot的启动类中添加@EnableScheduling 注解即可启动spring定时器任务配置。运行程序即可看到对应的输出。

原创粉丝点击