{"name":"@eggjs/schedule","version":"5.0.1","keywords":["egg","egg-plugin","eggPlugin","schedule","cron"],"author":{"name":"dead_horse"},"license":"MIT","_id":"@eggjs/schedule@5.0.1","maintainers":[{"name":"gxkl","email":"gxkl203@gmail.com"},{"name":"eggjs-admin","email":"fengmk2+eggjs@gmail.com"},{"name":"fengmk2","email":"fengmk2@gmail.com"},{"name":"atian25","email":"atian25@qq.com"},{"name":"dead_horse","email":"dead_horse@qq.com"},{"name":"wanghx","email":"whxaxes@gmail.com"},{"name":"hyj1991","email":"yeekwanvong@gmail.com"},{"name":"killagu","email":"killa07071201@gmail.com"},{"name":"coolme200","email":"2001-wms@163.com"},{"name":"mansonchor.zzw","email":"mansonchor1987@gmail.com"},{"name":"hubcarl","email":"hubcarl@126.com"},{"name":"gemwuu","email":"gemwuu@gmail.com"},{"name":"akitasummer","email":"644171127@qq.com"}],"homepage":"https://github.com/eggjs/egg-schedule#readme","bugs":{"url":"https://github.com/eggjs/egg-schedule/issues"},"dist":{"shasum":"b4fcb3248f2cc4dcc2bb59fa9b59154d25916747","tarball":"http://registry-npm.ywwl.com/@eggjs/schedule/download/@eggjs/schedule-5.0.1.tgz","fileCount":81,"integrity":"sha512-YeDhBCQfSGv9TtKN5x6i0Z+vq3XWvY59iKQbLEcHNIFNoEcB0k8O1l4Kuht4y40tffIg36r7W1yzrF2n4t3MTg==","signatures":[{"sig":"MEQCIGaqwn3lhSjQ1JI/Zy79+XdQe9SZ0zv1pGmInBLDin6wAiBD9Ptz0/18LbPwTsDKwnE427ANxLDWpMhcKORBpYnNkw==","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/@eggjs%2fschedule@5.0.1","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":134020,"size":27861,"noattachment":false,"key":"/@eggjs/schedule/-/@eggjs/schedule-5.0.1.tgz"},"main":"./dist/commonjs/index.js","tshy":{"exports":{".":"./src/index.ts","./package.json":"./package.json"}},"type":"module","types":"./dist/commonjs/index.d.ts","module":"./dist/esm/index.js","engines":{"node":">=18.19.0"},"exports":{".":{"import":{"types":"./dist/esm/index.d.ts","default":"./dist/esm/index.js"},"require":{"types":"./dist/commonjs/index.d.ts","default":"./dist/commonjs/index.js"}},"./package.json":"./package.json"},"gitHead":"d4603c2ae49a809d28c2f92e5c0f62b710daf83a","scripts":{"ci":"egg-bin cov","lint":"eslint --cache src test --ext .ts","test":"egg-bin test","preci":"npm run lint && npm run prepublishOnly && attw --pack","pretest":"npm run lint -- --fix && npm run prepublishOnly","prepublishOnly":"tshy && tshy-after"},"_npmUser":{"name":"fengmk2","email":"fengmk2@gmail.com"},"eggPlugin":{"name":"schedule","exports":{"import":"./dist/esm","require":"./dist/commonjs"}},"repository":{"url":"git+ssh://git@github.com/eggjs/egg-schedule.git","type":"git"},"_npmVersion":"10.8.2","description":"schedule plugin for egg, support corn job.","directories":{},"_nodeVersion":"18.20.5","dependencies":{"utility":"^2.1.0","is-type-of":"^2.1.0","cron-parser":"^4.9.0","humanize-ms":"^2.0.0","safe-timers":"^1.1.0","@eggjs/utils":"^4.0.3"},"publishConfig":{"access":"public"},"_hasShrinkwrap":false,"devDependencies":{"egg":"beta","tshy":"3","eslint":"8","egg-bin":"beta","egg-mock":"beta","egg-tracer":"2","tshy-after":"1","typescript":"5","@types/node":"22","@types/mocha":"10","egg-logrotator":"^3.2.0","@eggjs/tsconfig":"1","eslint-config-egg":"14","@types/safe-timers":"^1.1.2","@arethetypeswrong/cli":"^0.17.1"},"_npmOperationalInternal":{"tmp":"tmp/schedule_5.0.1_1734439705797_0.2265442040878658","host":"s3://npm-registry-packages-npm-production"},"readme":"# @eggjs/schedule\n\n[![NPM version][npm-image]][npm-url]\n[![Known Vulnerabilities][snyk-image]][snyk-url]\n[![npm download][download-image]][download-url]\n[![Node.js Version](https://img.shields.io/node/v/@eggjs/schedule.svg?style=flat)](https://nodejs.org/en/download/)\n\n[npm-image]: https://img.shields.io/npm/v/@eggjs/schedule.svg?style=flat-square\n[npm-url]: https://npmjs.org/package/@eggjs/schedule\n[snyk-image]: https://snyk.io/test/npm/@eggjs/schedule/badge.svg?style=flat-square\n[snyk-url]: https://snyk.io/test/npm/@eggjs/schedule\n[download-image]: https://img.shields.io/npm/dm/@eggjs/schedule.svg?style=flat-square\n[download-url]: https://npmjs.org/package/@eggjs/schedule\n\nA schedule plugin for egg, has been built-in plugin for egg enabled by default.\n\nIt's fully extendable for a developer and provides a simple built-in TimerStrategy.\n\n## Usage\n\nJust add your job file to `{baseDir}/app/schedule`.\n\n```ts\n// {baseDir}/app/schedule/cleandb.ts\nimport { Subscription } from 'egg';\n\nexport default class CleanDB extends Subscription {\n  /**\n   * @property {Object} schedule\n   *  - {String} type - schedule type, `worker` or `all` or your custom types.\n   *  - {String} [cron] - cron expression, see [below](#cron-style-scheduling)\n   *  - {Object} [cronOptions] - cron options, see [cron-parser#options](https://github.com/harrisiirak/cron-parser#options)\n   *  - {String | Number} [interval] - interval expression in millisecond or express explicitly like '1h'. see [below](#interval-style-scheduling)\n   *  - {Boolean} [immediate] - To run a scheduler at startup\n   *  - {Boolean} [disable] - whether to disable a scheduler, usually use in dynamic schedule\n   *  - {Array} [env] - only enable scheduler when match env list\n   */\n  static get schedule() {\n    return {\n      type: 'worker',\n      cron: '0 0 3 * * *',\n      // interval: '1h',\n      // immediate: true,\n    };\n  }\n\n  async subscribe() {\n    await this.ctx.service.db.cleandb();\n  }\n}\n```\n\nYou can also use function simply like:\n\n```ts\nimport { EggContext } from 'egg';\n\nexport const schedule = {\n  type: 'worker',\n  cron: '0 0 3 * * *',\n  // interval: '1h',\n  // immediate: true,\n};\n\nexport async function task(ctx: EggContext) {\n  await ctx.service.db.cleandb();\n}\n```\n\n## Overview\n\n`@eggjs/schedule` supports both cron-based scheduling and interval-based scheduling.\n\nSchedule decision is being made by `agent` process. `agent` triggers a task and sends a message to `worker` process. Then, one or all `worker` process(es) execute the task based on schedule type.\n\nTo setup a schedule task, simply create a job file in `{app_root}/app/schedule`. A file contains one job and exports `schedule` and `task` properties.\n\nThe rule of thumbs is one job per file.\n\n## Task\n\nTask is a class which will be instantiated with every schedule, and a `subscribe` method will be invoked.\n\nYou can get anonymous context with `this.ctx`.\n\n- ctx.method: `SCHEDULE`\n- ctx.path: `/__schedule?path=${schedulePath}&${schedule}`.\n\nTo create a task, `subscribe` can be a generator function or async function. For example:\n\n```ts\n// A simple logger example\nimport { Subscription } from 'egg';\n\nexport default class LoggerExample extends Subscription {\n  async subscribe() {\n    this.ctx.logger.info('Info about your task');\n  }\n}\n```\n\n```ts\n// A real world example: wipe out your database.\n// Use it with caution. :)\nimport { Subscription } from 'egg';\n\nexport default class CleanDB extends Subscription {\n  async subscribe() {\n    await this.ctx.service.db.cleandb();\n  }\n}\n```\n\n## Scheduling\n\n`schedule` is an object that contains one required property, `type`, and optional properties, `{ cron, cronOptions, interval, immediate, disable, env }`.\n\n### Cron-style Scheduling\n\nUse [cron-parser](https://github.com/harrisiirak/cron-parser).\n\n> Note: `cron-parser` support `second` as optional that is not supported by linux crontab.\n>\n> `@hourly / @daily / @weekly / @monthly / @yearly` is also supported.\n\n```bash\n*    *    *    *    *    *\n┬    ┬    ┬    ┬    ┬    ┬\n│    │    │    │    │    |\n│    │    │    │    │    └ day of week (0 - 7) (0 or 7 is Sun)\n│    │    │    │    └───── month (1 - 12)\n│    │    │    └────────── day of month (1 - 31)\n│    │    └─────────────── hour (0 - 23)\n│    └──────────────────── minute (0 - 59)\n└───────────────────────── second (0 - 59, optional)\n```\n\nExample:\n\n```ts\n// To execute task every 3 hours\nexport const schedule = {\n  type: 'worker',\n  cron: '0 0 */3 * * *',\n  cronOptions: {\n    // tz: 'Europe/Athens',\n  },\n};\n```\n\n### Interval-style Scheduling\n\nTo use `setInterval`, and support [ms](https://www.npmjs.com/package/ms) conversion style\n\nExample:\n\n```ts\n// To execute task every 3 hours\nexport const schedule = {\n  type: 'worker',\n  interval: '3h',\n};\n```\n\n**Notice: Egg built-in TimerStrategy will schedule each execution at a fix rate, regardless of its execution time. So you have to make sure that your actual execution time of your `task/subscribe` must be smaller than your delay time.**\n\n### Schedule Type\n\n**Build-in support is:**\n\n- `worker`: will be executed in one random worker when a schedule runs.\n- `all`: will be executed in all workers when a schedule runs.\n\n**Custom schedule:**\n\nTo create a custom schedule, simply extend `agent.ScheduleStrategy` and register it by `agent.schedule.use(type, clz)`.\nYou can schedule the task to be executed by one random worker or all workers with\nthe built-in method `this.sendOne(...args)` or `this.sendAll(...args)` which support params,\nit will pass to `subscribe(...args)` or `task(ctx, ...args)`.\n\n```ts\n// {baseDir}/agent.ts\nimport { Agent } from 'egg';\n\nexport default (agent: Agent) => {\n  class CustomStrategy extends agent.ScheduleStrategy {\n    start() {\n      // such as mq / redis subscribe\n      agent.notify.subscribe('remote_task', (data) => {\n        this.sendOne(data);\n      });\n    }\n  }\n\n  agent.schedule.use('custom', CustomStrategy);\n};\n```\n\nThen you could use it to defined your job:\n\n```ts\n// {baseDir}/app/schedule/other.ts\nimport { Subscription } from 'egg';\n\nexport default class ClusterTask extends Subscription {\n  static get schedule() {\n    return {\n      type: 'custom',\n    };\n  }\n\n  async subscribe(data) {\n    console.log('got custom data:', data);\n    await this.ctx.service.someTask.run();\n  }\n}\n```\n\n## Dynamic schedule\n\n```ts\n// {baseDir}/app/schedule/sync.ts\nimport { Application } from 'egg';\n\nexport default (app: Application) => {\n  class SyncTask extends app.Subscription {\n    static get schedule() {\n      return {\n        interval: 10000,\n        type: 'worker',\n        // only start task when hostname match\n        disable: require('os').hostname() !== app.config.sync.hostname,\n        // only start task at prod mode\n        env: ['prod'],\n      };\n    }\n\n    async subscribe() {\n      await this.ctx.sync();\n    }\n  }\n\n  return SyncTask;\n};\n```\n\n## Configuration\n\n### Logging\n\nSee `${appInfo.root}/logs/{app_name}/egg-schedule.log` which provided by [config.customLogger.scheduleLogger](https://github.com/eggjs/schedule/blob/master/src/config/config.default.ts).\n\n```ts\n// config/config.default.ts\nimport { EggAppConfig } from 'egg';\n\nexport default {\n  customLogger: {\n    scheduleLogger: {\n      // consoleLevel: 'NONE',\n      // file: path.join(appInfo.root, 'logs', appInfo.name, 'egg-schedule.log'),\n    },\n  },\n} as Partial<EggAppConfig>;\n```\n\n### Customize directory\n\nIf you want to add additional schedule directories, you can use this config.\n\n```ts\n// config/config.default.ts\nimport { EggAppConfig } from 'egg';\n\nexport default {\n  schedule: {\n    directory: ['path/to/otherSchedule'],\n  },\n} as Partial<EggAppConfig>;\n```\n\n## Testing\n\n`app.runSchedule(scheduleName)` is provided by `@eggjs/schedule` plugin only for test purpose.\n\nExample:\n\n```ts\nit('test a schedule task', async () => {\n  // get app instance\n  await app.runSchedule('clean_cache');\n});\n```\n\n## Questions & Suggestions\n\nPlease open an issue [here](https://github.com/eggjs/egg/issues).\n\n## License\n\n[MIT](LICENSE)\n\n## Contributors\n\n[![Contributors](https://contrib.rocks/image?repo=eggjs/egg)](https://github.com/eggjs/egg/graphs/contributors)\n\nMade with [contributors-img](https://contrib.rocks).\n","publish_time":1734439706006,"_cnpm_publish_time":1734439706006,"dist-tags":{"beta":"6.0.2-beta.27","latest":"6.1.0","rc":"6.0.2-rc.1"}}