SpringBoot-@Schedule定时任务

SpringBoot定时任务

    修改程序入口, 添加开启定时任务的注解
@SpringBootApplication
@EnableScheduling
public class SpringbootScheduleApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootScheduleApplication.class, args);
    }
}
    编写定时任务类@Component进行注解扫面
@Component
public 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)
@Component
public 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()));
    }
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值