Spring Boot入门教程-定时任务

来源:互联网 发布:淘宝外卖和口碑的区别 编辑:程序博客网 时间:2024/05/23 01:25

说到定时任务,用到最多的就是quartz,当然早spring 中使用quartz 也是需要一堆配置的,但是在Spring Boot 中定时任务同样带给我们惊喜。


1.创建一个定时任务类ScheduledTasks 并添加以下注解

@Component@Configurable@EnableScheduling

@EnableScheduled 这个注解表是这个类为定时任务类类

2.编写一个方法  并添加@scheduled注解

 //每1分钟执行一次    @Scheduled(cron = "0 */1 *  * * * ")    public void reportCurrentByCron(){        System.out.println ("定时任务启动: " + dateFormat ().format (new Date()));    }    private SimpleDateFormat dateFormat(){        return new SimpleDateFormat ("HH:mm:ss");    }
@scheduled 注解括号中是Cron表达式

全部代码为:

@Component@Configurable@EnableSchedulingpublic class ScheduledTasks {    //每1分钟执行一次    @Scheduled(cron = "0 */1 *  * * * ")    public void reportCurrentByCron(){        System.out.println ("定时任务启动: " + dateFormat ().format (new Date()));    }    private SimpleDateFormat dateFormat(){        return new SimpleDateFormat ("HH:mm:ss");    }}
3.启动后控制台信息:



定时任务就完成了。

原创粉丝点击