load_schedule.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. 'use strict';
  2. const path = require('path');
  3. const assert = require('assert');
  4. const is = require('is-type-of');
  5. module.exports = app => {
  6. const dirs = app.loader.getLoadUnits().map(unit => path.join(unit.path, 'app/schedule'));
  7. dirs.push(...app.config.schedule.directory);
  8. const Loader = getScheduleLoader(app);
  9. const schedules = app.schedules = {};
  10. new Loader({
  11. directory: dirs,
  12. target: schedules,
  13. inject: app,
  14. }).load();
  15. return schedules;
  16. };
  17. function getScheduleLoader(app) {
  18. return class ScheduleLoader extends app.loader.FileLoader {
  19. load() {
  20. const target = this.options.target;
  21. const items = this.parse();
  22. for (const item of items) {
  23. const schedule = item.exports;
  24. const fullpath = item.fullpath;
  25. assert(schedule.schedule, `schedule(${fullpath}): must have schedule and task properties`);
  26. assert(is.class(schedule) || is.function(schedule.task), `schedule(${fullpath}: schedule.task should be function or schedule should be class`);
  27. let task;
  28. if (is.class(schedule)) {
  29. task = async (ctx, data) => {
  30. const s = new schedule(ctx);
  31. s.subscribe = app.toAsyncFunction(s.subscribe);
  32. return s.subscribe(data);
  33. };
  34. } else {
  35. task = app.toAsyncFunction(schedule.task);
  36. }
  37. const env = app.config.env;
  38. const envList = schedule.schedule.env;
  39. if (is.array(envList) && !envList.includes(env)) {
  40. app.coreLogger.info(`[egg-schedule]: ignore schedule ${fullpath} due to \`schedule.env\` not match`);
  41. continue;
  42. }
  43. // handle symlink case
  44. const realFullpath = require.resolve(fullpath);
  45. target[realFullpath] = {
  46. schedule: schedule.schedule,
  47. task,
  48. key: realFullpath,
  49. };
  50. }
  51. }
  52. };
  53. }