十分钟!教你玩转SprintBoot定时任务

常用的定时任务有两种:

  1. 基于注解
  2. 基于接口
基于注解@Scheduled

@Service
public class Scheduling1Service {

    //每2秒执行一次(若上次任务执行时间超过2秒,则立即执行,否则从上一个任务开始时算起2秒后执行本次任务)
    @Scheduled(fixedRate = 2000)
    public void test1() throws InterruptedException {
        Thread.sleep(1000L);//模拟定时任务执行耗费了1s
        Thread.sleep(3000L);//模拟定时任务执行耗费了3s
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(format.format(date)+"==>SchedulingService.test1 is called");
    }

    //上一个任务执行完2秒后,再执行本次任务
    @Scheduled(fixedDelay = 2000)
    public void test2() throws InterruptedException {
        Thread.sleep(3000L);//模拟定时任务执行耗费了3s
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(format.format(date)+"==>SchedulingService.test2 is called");
    }

    //支持corn表达式
    @Scheduled(cron = "0 0 1 * * ?")//每天凌晨1点执行
    public void test3() throws InterruptedException {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(format.format(date)+"==>SchedulingService.test3 is called");
    }
}

注:不会写corn表达式的小伙伴,可以使用这个哦:https://cron.qqe2.com 会帮你自动生成corn表达式,且能检测你的表达式是否合法。非常好用!

以上三种是使用频次比较多的。因为不接受参数,主要用户定时同步第三方基础数据的业务场景。

使用@Scheduled需在pom中引用springboot的相关依赖,并在Application主入口函数中增加@EnableScheduling的注解。

基于接口形式的定时任务

基于注解的方式的任务配置起来很简单也很好用,但是由于不能传递参数,使用场景有限。那么就需要使用基于接口形式的定时任务了。

添加依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
@Service
public class Scheduling3Service implements SchedulingConfigurer {
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(
                new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("cccccccc");
                    }
                },
                triggerContext -> {
                    return new CronTrigger("0/1 * * * * ? ").nextExecutionTime(triggerContext);
                }
        );
    }
}

以上就是两种常用的定时任务,小伙伴们,你,学废了吗?

更多java原创阅读:https://javawu.com

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值