SpringBoot集成定时任务,整合Scheduled(一)

SpringBoot集成定时任务,整合Scheduled(一)

本次将对Scheduled进行整合

项目环境

  • IDEA 2019.1
  • SpringBoot 2.1.5
  • Gradle 4.10

整合步骤

@Scheduled

SpringBoot内置了定时任务Scheduled,能够很好的实现定时任务。

  • 在SpringBoot应用添加@EnableScheduling注解启动定时任务
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class FastSpringbootApplication {
    public static void main(String[] args) {
        SpringApplication.run(FastSpringbootApplication.class, args);
    }
}
  • 添加测试定时任务的代码。

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

@Component
public class ScheduledTask {

    @Scheduled(cron = "5 0 0 * * ?")
    public void scheduledTask1(){
        System.out.println("定时任务1");
    }

    @Scheduled(initialDelay =  1000 * 10,fixedDelay = 1000 * 5)
    public void scheduledTask2(){
        System.out.println("任务2执行时间:"+System.currentTimeMillis());
        System.out.println("定时任务2");
        try {
            Thread.sleep(2*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("任务2结束时间:"+System.currentTimeMillis());
    }

    @Scheduled(initialDelay =  1000 * 10,fixedRate = 1000 * 5)
    public void scheduledTask3(){
        System.out.println("任务3执行时间:"+System.currentTimeMillis());
        System.out.println("定时任务3");
        try {
            Thread.sleep(2*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("任务3结束时间:"+System.currentTimeMillis());
    }
}

  • corn表达式在linux使用广泛,具体可以参考cron表达式详解以及在线Cron表达式生成器
  • initialDelay:启动后多久开始执行,单位时毫秒
  • fixedRate:下次执行时间,任务开始运行的时候就计时。
  • fixedDelay:下次执行时间,fixedDelay等任务进行完了才开始计时
    关于fixedRate和fixedDelay的运行效果接下来详述,下面时运行一段时间的效果:
任务3执行时间:1558876357313
定时任务3
任务3结束时间:1558876359313
任务2执行时间:1558876359313
定时任务2
任务2结束时间:1558876361314
任务3执行时间:1558876362312
定时任务3
任务3结束时间:1558876364313
任务2执行时间:1558876366316
定时任务2
任务2结束时间:1558876368316
任务3执行时间:1558876368316
定时任务3
任务3结束时间:1558876370316
任务3执行时间:1558876372313
定时任务3
任务3结束时间:1558876374314
任务2执行时间:1558876374314
定时任务2
任务2结束时间:1558876376314
  • 任务3和任务2的第一次执行时间都是启动10S后开始执行,时间是1558876357313
  • 任务三fixedRate第一次开始时间1558876357313结束时间1558876359313中间间隔2S。任务三第二次执行时间1558876362312结束时间1558876364313。1558876362312(第二次开始时间)-1558876357313(第一次开始时间)=4999,等于5S。‬
  • 任务二fixedDelay第一次开始时间1558876359313,第一次结束时间1558876361314。第二次开始时间1558876366316,结束时间1558876368316
    1558876366316(第二次开始时间) - 1558876361314(第一次结束时间) = 5002排除唤醒任务的细微时间,等于5S

通过以上的示例,更容易理解。

项目代码

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值