schedule.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. 'use strict';
  2. const STRATEGY = Symbol('strategy');
  3. const STRATEGY_INSTANCE = Symbol('strategy_instance');
  4. const loadSchedule = require('./load_schedule');
  5. module.exports = class Schedule {
  6. constructor(agent) {
  7. this.agent = agent;
  8. this.logger = agent.getLogger('scheduleLogger');
  9. this[STRATEGY] = new Map();
  10. this[STRATEGY_INSTANCE] = new Map();
  11. this.closed = false;
  12. }
  13. /**
  14. * register a custom Schedule Strategy
  15. * @param {String} type - strategy type
  16. * @param {Strategy} clz - Strategy class
  17. */
  18. use(type, clz) {
  19. this[STRATEGY].set(type, clz);
  20. }
  21. /**
  22. * load all schedule jobs, then initialize and register speical strategy
  23. */
  24. init() {
  25. const scheduleItems = loadSchedule(this.agent);
  26. for (const k of Object.keys(scheduleItems)) {
  27. const { key, schedule } = scheduleItems[k];
  28. const type = schedule.type;
  29. if (schedule.disable) continue;
  30. // find speical Strategy
  31. const Strategy = this[STRATEGY].get(type);
  32. if (!Strategy) {
  33. const err = new Error(`schedule type [${type}] is not defined`);
  34. err.name = 'EggScheduleError';
  35. throw err;
  36. }
  37. // Initialize strategy and register
  38. const instance = new Strategy(schedule, this.agent, key);
  39. this[STRATEGY_INSTANCE].set(key, instance);
  40. }
  41. }
  42. /**
  43. * job finish event handler
  44. *
  45. * @param {Object} info - { key, success, message }
  46. */
  47. onJobFinish(info) {
  48. this.logger.debug(`[Job#${info.id}] ${info.key} finish event received by agent from worker#${info.workerId}`);
  49. const instance = this[STRATEGY_INSTANCE].get(info.key);
  50. /* istanbul ignore else */
  51. if (instance) {
  52. instance.onJobFinish(info);
  53. }
  54. }
  55. /**
  56. * start schedule
  57. */
  58. start() {
  59. this.closed = false;
  60. for (const instance of this[STRATEGY_INSTANCE].values()) {
  61. instance.start();
  62. }
  63. }
  64. close() {
  65. this.closed = true;
  66. }
  67. };