springboot使用@Scheduled实现定时任务

springboot使用@Scheduled实现定时任务

1.代码实现:

启动类添加注解

@SpringBootApplication
@EnableScheduling
public class ScheduleApplication {

    public static void main(String[] args) {
        SpringApplication.run(ScheduleApplication.class, args);
    }

}

添加定时任务类

@Component
@Slf4j
public class ScheduledTasks {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        log.info("现在时间:" + dateFormat.format(new Date()));
    }

}

@Scheduled的参数:

  • cron:通过cron表达式来配置执行规则
  • zone:cron表达式解析时使用的时区
  • fixedDelay:上一次执行结束到下一次执行开始的间隔时间(单位:ms)
  • fixedDelayString:上一次任务执行结束到下一次执行开始的间隔时间,使用java.time.Duration#parse解析
  • fixedRate:以固定间隔执行任务,即上一次任务执行开始到下一次执行开始的间隔时间(单位:ms),若在调度任务执行时,上一次任务还未执行完毕,会加入worker队列,等待上一次执行完成后立即执行下一次任务
  • fixedRateString:与fixedRate逻辑一致,只是使用java.time.Duration#parse解析
  • initialDelay:首次任务执行的延迟时间
  • initialDelayString:首次任务执行的延迟时间,使用java.time.Duration#parse解析

2.实现效果:

运行项目,查看控制台

2021-12-28 16:55:10.684  INFO 15924 --- [   scheduling-1] com.cxh.schedule.task.ScheduledTasks     : 现在时间:16:55:10
2021-12-28 16:55:15.681  INFO 15924 --- [   scheduling-1] com.cxh.schedule.task.ScheduledTasks     : 现在时间:16:55:15
2021-12-28 16:55:20.683  INFO 15924 --- [   scheduling-1] com.cxh.schedule.task.ScheduledTa
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值