SpringBoot源码解析-Scheduled定时器的原理

定时器原理剖析

定时器的基础是jdk中的工具类ScheduledThreadPoolExecutor,想要了解springboot定时器的原理,先得了解ScheduledThreadPoolExecutor的原理。

该类中有三个主要的方法:

  1. schedule(...)
  2. scheduleWithFixedDelay(...)
  3. scheduleAtFixedRate(...)

我们先简单回顾下这三个方法。

schedule方法

schedule方法的作用是提供一个延时执行的任务,该任务只会执行一次。该方法的三个参数如下

 
  1. schedule(Runnable command, long delay, TimeUnit unit)

  2. 复制代码

command为需要执行的任务,delay和unit组合起来使用,表示延时的时间。

 
  1. public ScheduledFuture<?> schedule(Runnable command,

  2. long delay,

  3. TimeUnit unit) {

  4. //校验参数

  5. if (command == null || unit == null)

  6. throw new NullPointerException();

  7. //任务转换

  8. RunnableScheduledFuture<?> t = decorateTask(command,

  9. new ScheduledFutureTask<Void>(command, null,

  10. triggerTime(delay, unit)));

  11. //添加任务到延时队列

  12. delayedExecute(t);

  13. return t;

  14. }

  15. 复制代码

首先看一下任务转换的逻辑:

 
  1. //将延时的时间加上现在的时间,转化成真正执行任务的时间

  2. private long triggerTime(long delay, TimeUnit unit) {

  3. return triggerTime(unit.toNanos((delay < 0) ? 0 : delay));

  4. }

  5. //将任务转化为ScheduledFutureTask对象

  6. ScheduledFutureTask(Runnable r, V result, long ns) {

  7. super(r, result);

  8. this.time = ns;

  9. //period为0表示只执行一次

  10. this.period = 0;

  11. this.sequenceNumber = sequencer.getAndIncrement();

  12. }

  13. 复制代码

接下来就是添加进任务队列:

 
  1. private void delayedExecute(RunnableScheduledFuture<?> task) {

  2. //检查任务状态

  3. if (isShutdown())

  4. reject(task);

  5. else {

  6. //添加进队列

  7. super.getQueue().add(task);

  8. //在执行之前,再次检查任务状态

  9. if (isShutdown() &&

  10. !canRunInCurrentRunState(task.isPeriodic()) &&

  11. remove(task))

  12. task.cancel(false);

  13. else

  14. //检查是否有线程在处理任务,如果工作线程数少于核心线程数,会新建worker。

  15. ensurePrestart();

  16. }

  17. }

  18. 复制代码

添加的逻辑看完了,现在看一下加入队列后是如何执行的:

 
  1. //worker线程会调用刚刚封装好的ScheduledFutureTask对象的run方法

  2. public void run() {

  3. //判断period是否是0

  4. boolean periodic = isPeriodic();

  5. if (!canRunInCurrentRunState(periodic))

  6. cancel(false);

  7. else if (!periodic)

  8. //在schedule方法中period是0,进入父类的run方法,run方法中

  9. //会调用我们传入的任务

  10. ScheduledFutureTask.super.run();

  11. else if (ScheduledFutureTask.super.runAndReset()) {

  12. setNextRunTime();

  13. reExecutePeriodic(outerTask);

  14. }

  15. }

  16. 复制代码

schedule方法的执行逻辑大致如上,schedule方法只执行一次。

scheduleWithFixedDelay方法

该方法的作用是在任务执行完成后,经过固定延时时间再次运行。

 
  1. public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,

  2. long initialDelay,

  3. long delay,

  4. TimeUnit unit) {

  5. //校验参数

  6. if (command == null || unit == null)

  7. throw new NullPointerException();

  8. if (delay <= 0)

  9. throw new IllegalArgumentException();

  10. //将任务转化为ScheduledFutureTask对象,注意这个地方period不是0了!

  11. ScheduledFutureTask<Void> sft =

  12. new ScheduledFutureTask<Void>(command,

  13. null,

  14. triggerTime(initialDelay, unit),

  15. unit.toNanos(-delay));

  16. //将outerTask设置为自己

  17. RunnableScheduledFuture<Void> t = decorateTask(command, sft);

  18. sft.outerTask = t;

  19. //添加进延时队列

  20. delayedExecute(t);

  21. return t;

  22. }

  23. 复制代码

和schedule方法稍有不同,一个是period不在是0,而是小于0,还有就是将outerTask设置为自己。

添加进任务队列的逻辑都是一样的,所以直接看执行逻辑:

 
  1. public void run() {

  2. //这个地方periodic是true了

  3. boolean periodic = isPeriodic();

  4. if (!canRunInCurrentRunState(periodic))

  5. cancel(false);

  6. else if (!periodic)

  7. ScheduledFutureTask.super.run();

  8. //所以会进入下面这个逻辑

  9. else if (ScheduledFutureTask.super.runAndReset()) {

  10. //设置下一次任务时间

  11. setNextRunTime();

  12. //将自己再次添加进队列

  13. reExecutePeriodic(outerTask);

  14. }

  15. }

  16. //period是小于0的,注意这个地方大于0和小于0逻辑上的区别

  17. private void setNextRunTime() {

  18. long p = period;

  19. if (p > 0)

  20. //大于0的话,是用上次执行的时间,加上延时时间算出下次执行的时间

  21. time += p;

  22. else

  23. //小于0的话,是用当前时间,加上延时时间,算出下次执行时间

  24. time = triggerTime(-p);

  25. }

  26. 复制代码

scheduleAtFixedRate方法

这个方法和上一个方法几乎一样,唯一的区别就是他的period是大于0的,所以延时时间按照大于0来计算。


springboot中定时器的原理

了解完ScheduledThreadPoolExecutor的基础原理后,我们来看一下springboot中定时任务的调度。springboot定时任务调度的基础是ScheduledAnnotationBeanPostProcessor类,查看继承体系发现该类实现了BeanPostProcessor接口,所以进入该类的postProcessAfterInitialization方法。

 
  1. public Object postProcessAfterInitialization(Object bean, String beanName) {

  2. if (bean instanceof AopInfrastructureBean || bean instanceof TaskScheduler ||

  3. bean instanceof ScheduledExecutorService) {

  4. // Ignore AOP infrastructure such as scoped proxies.

  5. return bean;

  6. }

  7. Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean);

  8. if (!this.nonAnnotatedClasses.contains(targetClass)) {

  9. //查找被Scheduled注解标注的类

  10. Map<Method, Set<Scheduled>> annotatedMethods = MethodIntrospector.selectMethods(targetClass,

  11. (MethodIntrospector.MetadataLookup<Set<Scheduled>>) method -> {

  12. Set<Scheduled> scheduledMethods = AnnotatedElementUtils.getMergedRepeatableAnnotations(

  13. method, Scheduled.class, Schedules.class);

  14. return (!scheduledMethods.isEmpty() ? scheduledMethods : null);

  15. });

  16. if (annotatedMethods.isEmpty()) {

  17. this.nonAnnotatedClasses.add(targetClass);

  18. if (logger.isTraceEnabled()) {

  19. logger.trace("No @Scheduled annotations found on bean class: " + targetClass);

  20. }

  21. }

  22. else {

  23. // Non-empty set of methods

  24. //如果被Scheduled注解标注,就执行processScheduled方法。

  25. annotatedMethods.forEach((method, scheduledMethods) ->

  26. scheduledMethods.forEach(scheduled -> processScheduled(scheduled, method, bean)));

  27. if (logger.isTraceEnabled()) {

  28. logger.trace(annotatedMethods.size() + " @Scheduled methods processed on bean '" + beanName +

  29. "': " + annotatedMethods);

  30. }

  31. }

  32. }

  33. return bean;

  34. }

  35. //以cron模式来解析一下processScheduled方法

  36. protected void processScheduled(Scheduled scheduled, Method method, Object bean) {

  37. try {

  38. Runnable runnable = createRunnable(bean, method);

  39. boolean processedSchedule = false;

  40. ...

  41. // 解析注解里的属性

  42. String cron = scheduled.cron();

  43. if (StringUtils.hasText(cron)) {

  44. String zone = scheduled.zone();

  45. if (this.embeddedValueResolver != null) {

  46. cron = this.embeddedValueResolver.resolveStringValue(cron);

  47. zone = this.embeddedValueResolver.resolveStringValue(zone);

  48. }

  49. if (StringUtils.hasLength(cron)) {

  50. Assert.isTrue(initialDelay == -1, "'initialDelay' not supported for cron triggers");

  51. processedSchedule = true;

  52. if (!Scheduled.CRON_DISABLED.equals(cron)) {

  53. TimeZone timeZone;

  54. if (StringUtils.hasText(zone)) {

  55. timeZone = StringUtils.parseTimeZoneString(zone);

  56. }

  57. else {

  58. timeZone = TimeZone.getDefault();

  59. }

  60. //将封装好的任务存储起来

  61. tasks.add(this.registrar.scheduleCronTask(new CronTask(runnable, new CronTrigger(cron, timeZone))));

  62. }

  63. }

  64. }

  65. ...

  66. // Finally register the scheduled tasks

  67. synchronized (this.scheduledTasks) {

  68. Set<ScheduledTask> regTasks = this.scheduledTasks.computeIfAbsent(bean, key -> new LinkedHashSet<>(4));

  69. //根据bean分类,将每个bean的定时任务存进scheduledTasks

  70. regTasks.addAll(tasks);

  71. }

  72. }

  73. ...

  74. }

  75. public ScheduledTask scheduleCronTask(CronTask task) {

  76. ScheduledTask scheduledTask = this.unresolvedTasks.remove(task);

  77. boolean newTask = false;

  78. if (scheduledTask == null) {

  79. //根据task,新建一个ScheduledTask

  80. scheduledTask = new ScheduledTask(task);

  81. newTask = true;

  82. }

  83. if (this.taskScheduler != null) {

  84. scheduledTask.future = this.taskScheduler.schedule(task.getRunnable(), task.getTrigger());

  85. }

  86. else {

  87. //根据定时任务种类的区别存储task

  88. addCronTask(task);

  89. this.unresolvedTasks.put(task, scheduledTask);

  90. }

  91. return (newTask ? scheduledTask : null);

  92. }

  93. 复制代码

在postProcessAfterInitialization方法中,spring主要就是解析注解,并将根据注解生成相应的延时任务。那么现在解析好了,也存储好了,执行的地方在哪里呢?在一次查看该类的继承体系,发现该类还实现了ApplicationListener接口,所以进入onApplicationEvent方法。

 
  1. public void onApplicationEvent(ContextRefreshedEvent event) {

  2. if (event.getApplicationContext() == this.applicationContext) {

  3. finishRegistration();

  4. }

  5. }

  6. private void finishRegistration() {

  7. ...

  8. //上面一大段都是寻找taskScheduler类的,如果没有设置的话这边是找不到的

  9. this.registrar.afterPropertiesSet();

  10. }

  11. public void afterPropertiesSet() {

  12. scheduleTasks();

  13. }

  14. protected void scheduleTasks() {

  15. //没有自定义配置就使用默认配置

  16. if (this.taskScheduler == null) {

  17. //默认的执行器只有一个线程使用的时候要注意一下

  18. this.localExecutor = Executors.newSingleThreadScheduledExecutor();

  19. this.taskScheduler = new ConcurrentTaskScheduler(this.localExecutor);

  20. }

  21. if (this.triggerTasks != null) {

  22. for (TriggerTask task : this.triggerTasks) {

  23. addScheduledTask(scheduleTriggerTask(task));

  24. }

  25. }

  26. if (this.cronTasks != null) {

  27. for (CronTask task : this.cronTasks) {

  28. addScheduledTask(scheduleCronTask(task));

  29. }

  30. }

  31. if (this.fixedRateTasks != null) {

  32. for (IntervalTask task : this.fixedRateTasks) {

  33. addScheduledTask(scheduleFixedRateTask(task));

  34. }

  35. }

  36. if (this.fixedDelayTasks != null) {

  37. for (IntervalTask task : this.fixedDelayTasks) {

  38. addScheduledTask(scheduleFixedDelayTask(task));

  39. }

  40. }

  41. }

  42. 复制代码

在该方法中,清晰的看到了定时任务调用的过程triggerTasks好像不是通过注解进来的,这个先不管。我们可以看一下另外三个的执行。

cron执行逻辑

 
  1. public ScheduledTask scheduleCronTask(CronTask task) {

  2. ScheduledTask scheduledTask = this.unresolvedTasks.remove(task);

  3. ...

  4. //这个地方taskScheduler已经有默认值了

  5. if (this.taskScheduler != null) {

  6. scheduledTask.future = this.taskScheduler.schedule(task.getRunnable(), task.getTrigger());

  7. }

  8. ...

  9. return (newTask ? scheduledTask : null);

  10. }

  11. public ScheduledFuture<?> schedule(Runnable task, Trigger trigger) {

  12. try {

  13. ...

  14. else {

  15. ...

  16. //新建了一个ReschedulingRunnable对象,调用schedule方法。

  17. return new ReschedulingRunnable(task, trigger, this.scheduledExecutor, errorHandler).schedule();

  18. }

  19. }

  20. ...

  21. }

  22. //新建一个ReschedulingRunnable对象,这个对象也实现了runnable接口

  23. public ReschedulingRunnable(

  24. Runnable delegate, Trigger trigger, ScheduledExecutorService executor, ErrorHandler errorHandler) {

  25. super(delegate, errorHandler);

  26. this.trigger = trigger;

  27. this.executor = executor;

  28. }

  29. public ScheduledFuture<?> schedule() {

  30. synchronized (this.triggerContextMonitor) {

  31. this.scheduledExecutionTime = this.trigger.nextExecutionTime(this.triggerContext);

  32. if (this.scheduledExecutionTime == null) {

  33. return null;

  34. }

  35. //计算下次执行时间

  36. long initialDelay = this.scheduledExecutionTime.getTime() - System.currentTimeMillis();

  37. //将自己传入执行器,也就是调用自己的run方法

  38. this.currentFuture = this.executor.schedule(this, initialDelay, TimeUnit.MILLISECONDS);

  39. return this;

  40. }

  41. }

  42. public void run() {

  43. Date actualExecutionTime = new Date();

  44. //执行我们定义的定时任务

  45. super.run();

  46. Date completionTime = new Date();

  47. synchronized (this.triggerContextMonitor) {

  48. Assert.state(this.scheduledExecutionTime != null, "No scheduled execution");

  49. //更新时间

  50. this.triggerContext.update(this.scheduledExecutionTime, actualExecutionTime, completionTime);

  51. if (!obtainCurrentFuture().isCancelled()) {

  52. //在次调用schedule方法

  53. schedule();

  54. }

  55. }

  56. }

  57. 复制代码

在上面我们分析执行器逻辑的时候,知道执行器的schedule方法只会执行一次,所以springboot在这个地方使用互相调用的方法,来达到定时循环的目的。所以这个方法中,关键的就是时间的更新。

 
  1. public Date nextExecutionTime(TriggerContext triggerContext) {

  2. //获取上一次任务完成时间

  3. Date date = triggerContext.lastCompletionTime();

  4. if (date != null) {

  5. //获取上一次任务执行的时间

  6. Date scheduled = triggerContext.lastScheduledExecutionTime();

  7. //比较两次时间,使用后者生成新的执行时间

  8. if (scheduled != null && date.before(scheduled)) {

  9. date = scheduled;

  10. }

  11. }

  12. else {

  13. //初始化的时候直接使用当前时间

  14. date = new Date();

  15. }

  16. return this.sequenceGenerator.next(date);

  17. }

  18. 复制代码

cron模式每次根据上次执行时间和上次完成时间更后面的生成新的时间,结合肥朝的文章应该可以理解这种模型。不过这个地方我也不太明白什么情况下完成时间会在执行时间的前面。反正就是根据最新的时间生成新的时间就是。

剩下的两个执行逻辑

 
  1. public ScheduledTask scheduleFixedRateTask(IntervalTask task) {

  2. FixedRateTask taskToUse = (task instanceof FixedRateTask ? (FixedRateTask) task :

  3. new FixedRateTask(task.getRunnable(), task.getInterval(), task.getInitialDelay()));

  4. return scheduleFixedRateTask(taskToUse);

  5. }

  6. public ScheduledTask scheduleFixedRateTask(FixedRateTask task) {

  7. ...

  8. scheduledTask.future =

  9. this.taskScheduler.scheduleAtFixedRate(task.getRunnable(), task.getInterval());

  10. ...

  11. return (newTask ? scheduledTask : null);

  12. }

  13. public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period) {

  14. try {

  15. return this.scheduledExecutor.scheduleAtFixedRate(decorateTask(task, true), 0, period, TimeUnit.MILLISECONDS);

  16. }

  17. catch (RejectedExecutionException ex) {

  18. throw new TaskRejectedException("Executor [" + this.scheduledExecutor + "] did not accept task: " + task, ex);

  19. }

  20. }

  21. 复制代码

另外两个模式就是执行ScheduledThreadPoolExecutor对应的方法了,关键还是时间的逻辑,时间的生成逻辑上面已经给出来了,就是根据period大于0还是小于0来生成的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值