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
'use strict';
 
const path = require('path');
const assert = require('assert');
const is = require('is-type-of');
 
module.exports = app => {
  const dirs = app.loader.getLoadUnits().map(unit => path.join(unit.path, 'app/schedule'));
  dirs.push(...app.config.schedule.directory);
 
  const Loader = getScheduleLoader(app);
  const schedules = app.schedules = {};
  new Loader({
    directory: dirs,
    target: schedules,
    inject: app,
  }).load();
  return schedules;
};
 
function getScheduleLoader(app) {
  return class ScheduleLoader extends app.loader.FileLoader {
    load() {
      const target = this.options.target;
      const items = this.parse();
      for (const item of items) {
        const schedule = item.exports;
        const fullpath = item.fullpath;
        assert(schedule.schedule, `schedule(${fullpath}): must have schedule and task properties`);
        assert(is.class(schedule) || is.function(schedule.task), `schedule(${fullpath}: schedule.task should be function or schedule should be class`);
 
        let task;
        if (is.class(schedule)) {
          task = (ctx, data) => {
            const s = new schedule(ctx);
            s.subscribe = app.toAsyncFunction(s.subscribe);
            return s.subscribe(data);
          };
        } else {
          task = app.toAsyncFunction(schedule.task);
        }
 
        const env = app.config.env;
        const envList = schedule.schedule.env;
        if (is.array(envList) && !envList.includes(env)) {
          app.coreLogger.info(`[egg-schedule]: ignore schedule ${fullpath} due to \`schedule.env\` not match`);
          continue;
        }
 
        target[fullpath] = {
          schedule: schedule.schedule,
          task,
          key: fullpath,
        };
      }
    }
  };
}