SpringBoot实现定时任务

前言

在最近的面试中,面试官问到了定时器相关的知识,这里总结一下,在实际开发中,很多时候都会需要用到定时任务,能够自动执行所需要执行的方法,下面我介绍下在Springboot中如何配置定时任务。

开启定时任务

package com.ljh.springbootschedule.controller;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author shenyi
 * @data 2022/10/13
 * @apiNote
 */
@Component
@EnableScheduling //开启定时任务
public class scheduleController {

    @Async //开启异步
    @Scheduled(cron = "0/5 * * * * ?") //5s执行一次
    public void scheduleDemo(){
        System.out.println("执行第一个定时器..."+ LocalDateTime.now().toLocalTime());
        System.out.println();
    }

    @Async
    @Scheduled(cron = "0/6 * * * * ?")
    public void scheduleDemo1(){
        System.out.println("执行第二个定时器..."+ LocalDateTime.now().toLocalTime());
        System.out.println();
    }

}

其中@Scheduled(cron = “0/5 * * * * ?”)这个注解的 cron参数对应着 秒 分 时 日 月 年

具体参数规则如下

image-20221013164448645

示例:

表达式意义
每隔5秒钟执行一次*/5 * * * * ?
每隔1分钟执行一次每天1点执行一次0 * /1 * * * ?
每天23点55分执行一次0 55 23 * * ?
每月最后一天23点执行一次0 0 23 L * ?
每周六8点执行一次0 0 8 ? * L
每月最后一个周五,每隔2小时执行一次0 0 */2 ? * 6L
每月的第三个星期五上午10:15执行一次0 15 10 ? * 5#3
在每天下午2点到下午2:05期间的每1分钟执行0 0-5 14 * * ?
表示周一到周五每天上午10:15执行0 15 10 ? * 2-6

结果:

image-20221013165028401

测试完成,大家来自己动手试试吧。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值