eggjs/egg-schedule

Name: egg-schedule

Owner: egg

Description: Schedule plugin for egg

Created: 2016-07-15 08:36:28.0

Updated: 2018-03-27 02:35:32.0

Pushed: 2018-02-24 05:42:51.0

Homepage: null

Size: 95

Language: JavaScript

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

egg-schedule

NPM version build status Test coverage David deps Known Vulnerabilities npm download

A schedule plugin for egg. It supports two scheduler types, worker and all, and can be extended by other plugins.

egg-schedule has been built-in for egg. It is enabled by default.

Usage

Just add you job file to {app_root}/app/schedule.

app_root}/app/schedule/cleandb.js
t Subscription = require('egg').Subscription;

s CleanDB extends Subscription {
*
 @property {Object} schedule
  - {String} type - schedule type, `worker` or `all`
  - {String} [cron] - cron expression, see [below](#cron-style-scheduling)
  - {Object} [cronOptions] - cron options, see [cron-parser#options](https://github.com/harrisiirak/cron-parser#options)
  - {String | Number} [interval] - interval expression in millisecond or express explicitly like '1h'. see [below](#interval-style-scheduling)
  - {Boolean} [immediate] - To run a scheduler at startup
  - {Boolean} [disable] - whether to disable a scheduler, usually use in dynamic schedule
/
atic get schedule() {
return {
  type: 'worker',
  cron: '0 0 3 * * *',
  // interval: '1h',
  // immediate: true,
};


ync subscribe() {
await this.ctx.service.db.cleandb();



le.exports = CleanDB;

You can also use function simply.

rts.schedule = {
pe: 'worker',
on: '0 0 3 * * *',
 interval: '1h',
 immediate: true,


rts.task = async function (ctx) {
ait ctx.service.db.cleandb();

Overview

egg-schedule supports both time-based scheduling and interval-based scheduling.

Schedule decision is being made by agent process. agent triggers a task and sends message to worker process. Then, one or all worker process(es) execute the task based on schedule type.

To setup a schedule task, simply create a job file in {app_root}/app/schedule. A file contains one job and export schedule and task properties.

The rule of thumbs is one job per file.

Task

Task is a class which will be instantiated every schedule, and subscribe method will be invoked.

You can get anonymous context with this.ctx.

To create a task, subscribe can be generator function or async function. For example:

 simple logger example
t Subscription = require('egg').Subscription;
s LoggerExample extends Subscription {
subscribe() {
this.ctx.logger.info('Info about your task');


s
 real world example: wipe out your database.
se it with caution. :)
t Subscription = require('egg').Subscription;
s CleanDB extends Subscription {
ync subscribe() {
await this.ctx.service.db.cleandb();


Scheduling

schedule is an object that contains one required property, type, and optional properties, { cron, cronOptions, interval, immediate, disable }.

Cron-style Scheduling

Use cron-parser.

Note: cron-parser support second as optional that is not supported by linux crontab.

@hourly / @daily / @weekly / @monthly / @yearly is also supported.

 *    *    *    *    *
 ?    ?    ?    ?    ?
 ?    ?    ?    ?    |
 ?    ?    ?    ?    ? day of week (0 - 7) (0 or 7 is Sun)
 ?    ?    ?    ?????? month (1 - 12)
 ?    ?    ??????????? day of month (1 - 31)
 ?    ???????????????? hour (0 - 23)
 ????????????????????? minute (0 - 59)
?????????????????????? second (0 - 59, optional)

Example:

o execute task every 3 hours
rts.schedule = {
pe: 'worker',
on: '0 0 */3 * * *',
onOptions: {
// tz: 'Europe/Athens',


Interval-style Scheduling

To use setInterval, and support ms conversion style

Example:

o execute task every 3 hours
rts.schedule = {
pe: 'worker',
terval: '3h',

Schedule Type

Build-in support is:

Custom schedule

To create a custom schedule, simply extend agent.ScheduleStrategy and register it by agent.schedule.use(type, clz). You can schedule the task to be executed by one random worker or all workers with the built-in method this.sendOne(...args) or this.sendAll(...args) which support params, it will pass to subscribe(...args) or task(ctx, ...args).

app_root}/agent.js
le.exports = function(agent) {
ass CustomStrategy extends agent.ScheduleStrategy {
start() {
  // such as mq / redis subscribe
  agent.notify.subscribe('remote_task', data =>
    this.sendOne(data);
  });
}

ent.schedule.use('custsom', CustomStrategy);

Then you could use it to defined your job:

app_root}/app/schedule/other.js
t Subscription = require('egg').Subscription;
s ClusterTask extends Subscription {
atic get schedule() {
return {
  type: 'custom',
};

ync subscribe(data) {
console.log('got custom data:', data);
await this.ctx.service.someTask.run();


Dynamic schedule
app_root}/app/schedule/sync.js
le.exports = app => {
ass SyncTask extends app.Subscription {
static get schedule() {
  return {
    interval: 10000,
    type: 'worker',
    // only start task when hostname match
    disable: require('os').hostname() !== app.config.sync.hostname
  };
}
async subscribe() {
  await ctx.sync();
}

turn SyncTask;

Logging

See ${appInfo.root}/logs/{app_name}/egg-schedule.log which provided by config.customLogger.scheduleLogger.

onfig/config.default.js
ig.customLogger = {
heduleLogger: {
// consoleLevel: 'NONE',
// file: path.join(appInfo.root, 'logs', appInfo.name, 'egg-schedule.log'),


Testing

app.runSchedule(scheduleName) is provided by egg-schedule plugin only for test purpose.

Example:

test a schedule task', async function () {
 get app instance
ait app.runSchedule('clean_cache');

Questions & Suggestions

Please open an issue here.

License

MIT


This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.