333
schangxiang@126.com
2025-09-19 18966e02fb573c7e2bb0c6426ed792b38b910940
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
'use strict';
 
const Strategy = require('./base');
const parser = require('cron-parser');
const ms = require('humanize-ms');
const safetimers = require('safe-timers');
const assert = require('assert');
const utility = require('utility');
const is = require('is-type-of');
const CRON_INSTANCE = Symbol('cron_instance');
 
module.exports = class TimerStrategy extends Strategy {
  constructor(...args) {
    super(...args);
 
    const { interval, cron, cronOptions, immediate } = this.schedule;
    assert(interval || cron || immediate, `[egg-schedule] ${this.key} schedule.interval or schedule.cron or schedule.immediate must be present`);
    assert(is.function(this.handler), '[egg-schedule] ${this.key} strategy should override `handler()` method');
 
    // init cron parser
    if (cron) {
      try {
        this[CRON_INSTANCE] = parser.parseExpression(cron, cronOptions);
      } catch (err) {
        err.message = `[egg-schedule] ${this.key} parse cron instruction(${cron}) error: ${err.message}`;
        throw err;
      }
    }
  }
 
  start() {
    /* istanbul ignore next */
    if (this.agent.schedule.closed) return;
 
    if (this.schedule.immediate) {
      this.logger.info(`[Timer] ${this.key} next time will execute immediate`);
      setImmediate(() => this.handler());
    } else {
      this._scheduleNext();
    }
  }
 
  _scheduleNext() {
    /* istanbul ignore next */
    if (this.agent.schedule.closed) return;
 
    // get next tick
    const nextTick = this.getNextTick();
 
    if (nextTick) {
      this.logger.info(`[Timer] ${this.key} next time will execute after ${nextTick}ms at ${utility.logDate(new Date(Date.now() + nextTick))}`);
      this.safeTimeout(() => this.handler(), nextTick);
    } else {
      this.logger.info(`[Timer] ${this.key} reach endDate, will stop`);
    }
  }
 
  onJobStart() {
    // Next execution will trigger task at a fix rate, regardless of its execution time.
    this._scheduleNext();
  }
 
  /**
   * calculate next tick
   *
   * @return {Number} time interval, if out of range then return `undefined`
   */
  getNextTick() {
    // interval-style
    if (this.schedule.interval) return ms(this.schedule.interval);
 
    // cron-style
    if (this[CRON_INSTANCE]) {
      // calculate next cron tick
      const now = Date.now();
      let nextTick;
      let nextInterval;
 
      // loop to find next feature time
      do {
        try {
          nextInterval = this[CRON_INSTANCE].next();
          nextTick = nextInterval.getTime();
        } catch (err) {
          // Error: Out of the timespan range
          return;
        }
      } while (now >= nextTick);
 
      return nextTick - now;
    }
  }
 
  safeTimeout(handler, delay, ...args) {
    const fn = delay < safetimers.maxInterval ? setTimeout : safetimers.setTimeout;
    return fn(handler, delay, ...args);
  }
};