EggJS provides Schedule mechanism to perform some scheduled tasks

To better support clustering, EggBornJS reconstructed schedule based on repeatable job of bullmq, and has two advantages as follows:

  1. Can be compiled
  2. Easy to develop

Next, we will develop a Schedule, which print schedule invoked: Hello World on the console every 3 seconds

Declaration of Schedule

src/module/test-party/backend/src/config/config.js

module.exports = appInfo => {
  const config = {};

  // schedules
  config.schedules = {
    scheduleDemo: {
      path: 'test/schedule',
      instance: true,
      repeat: {
        every: 3 * 1000,
      },
    },
  };

  return config;
};
Name Description
scheduleDemo Schedule Name
path API Route to be performed
instance Whether to inject instance object into the context when the API Route performed
repeat Timing Interval, see also: repeatable job

What is the nature of attribute instance?

  • We mentioned earlier that EggBornJS supports multiple instances. Because schedule is triggered by the system, there is no instance information in the context
  • If instance set to false, the API Route needs to handle the logic related to multiple instances by itself
  • If instance set to true, the system will automatically loop multiple instances, perform API Route in turn, and inject instance object into the context environment, thus simplifying the development workload of API Route

Declaration of API Route

src/module/test-party/backend/src/routes.js

{ method: 'post', path: 'test/schedule', controller: test, middlewares: 'inner',
  meta: { auth: { enable: false } },
},
Name Description
middlewares Specify the middleware inner, only allowed performed inner access
auth.enable Disable the middleware auth

Why disable the global middleware auth?

  • Because Schedule is triggered by the system, there is no user information in its context

Controller Action

src/module/test-party/backend/src/controller/test.js

async schedule() {
  console.log('schedule invoked: ', 'Hello World');
  this.ctx.success();
}