SpringBoot-@Schedule定时任务

来源:互联网 发布:淘宝装修服务市场 编辑:程序博客网 时间:2024/05/18 09:58

SpringBoot定时任务

    修改程序入口, 添加开启定时任务的注解
@SpringBootApplication@EnableSchedulingpublic class SpringbootScheduleApplication {    public static void main(String[] args) {        SpringApplication.run(SpringbootScheduleApplication.class, args);    }}
    编写定时任务类@Component进行注解扫面
@Componentpublic class ScheduleTask  {    private  static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");    @Scheduled(fixedRate = 3000)    public void reportCurrentTime(){        System.out.println("当前时间:" + dateFormat.format(new Date()));    }}
程序将在启动后每3秒执行

这里写图片描述

@Scheduled(fixedRate = 3000):定时器将在每隔3秒执行

@Schedule(fixedDelay = 3000):定时器将在延迟3秒后每隔3秒执行

@Schedule(initialDelay = 1000, fiexdDelay = 3000):定时器将在1秒后每隔3秒执行

@Schedule(cron = “* * * * * ?”)

    一个cron表达式有至少6个(也可能7个)有空格分隔的时间元素。    按顺序依次为    秒(0~59)    分钟(0~59)    小时(0~23)    天(月)(0~31,但是你需要考虑你月的天数)    月(0~11)    天(星期)(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT)    7.年份(1970-2099)
@Componentpublic class ScheduleTask  {    private  static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");    @Scheduled(fixedRate = 3000)    public void reportCurrentTime(){        System.out.println("当前时间:" + dateFormat.format(new Date()));    }    //第一次延迟1秒执行,当执行完后3秒再执行    @Scheduled(initialDelay = 1000, fixedDelay = 3000)    public void timerInit() {        System.out.println("init : "+dateFormat.format(new Date()));    }    //每天19点50分50秒时执行    @Scheduled(cron = "50 50 19 * * ?")    public void timerCron() {        System.out.println("current time : "+ dateFormat.format(new Date()));    }}
1 0