{"name":"@eggjs/schedule","version":"6.0.2-beta.7","keywords":["cron","egg","egg-plugin","eggPlugin","schedule"],"author":{"name":"dead_horse"},"license":"MIT","_id":"@eggjs/schedule@6.0.2-beta.7","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":"hyj1991","email":"yeekwanvong@gmail.com"},{"name":"killagu","email":"killa07071201@gmail.com"},{"name":"coolme200","email":"2001-wms@163.com"},{"name":"akitasummer","email":"644171127@qq.com"},{"name":"niania","email":"ljracm@gmail.com"}],"homepage":"https://github.com/eggjs/egg/tree/next/plugins/schedule","bugs":{"url":"https://github.com/eggjs/egg/issues"},"dist":{"shasum":"c53e26cda97de851798ffbc5572fc8e04fb14cb1","tarball":"http://registry-npm.ywwl.com/@eggjs/schedule/download/@eggjs/schedule-6.0.2-beta.7.tgz","fileCount":35,"integrity":"sha512-ZOuzN6RIO4UNSpQa61HuMv4Asb/XSJbGCZmkUJUyfrZPgBBzuI8gRilWBTobeS7ztDHfCwXO2sjq6QJWP6nrfQ==","signatures":[{"sig":"MEUCIFwNH3tOTIqyALfzPTRU6aJdZNVWa5ccAAiQrA0XPUAXAiEAodsMLDenz/bsWTz2gpttqCbXCETUUudUdZEbNlaC9zY=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/@eggjs%2fschedule@6.0.2-beta.7","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":37271,"size":11181,"noattachment":false,"key":"/@eggjs/schedule/-/@eggjs/schedule-6.0.2-beta.7.tgz"},"main":"./dist/index.js","type":"module","_from":"file:eggjs-schedule-6.0.2-beta.7.tgz","types":"./dist/index.d.ts","module":"./dist/index.js","engines":{"node":">=22.18.0"},"exports":{".":"./dist/index.js","./app":"./dist/app.js","./agent":"./dist/agent.js","./types":"./dist/types.js","./lib/types":"./dist/lib/types.js","./lib/schedule":"./dist/lib/schedule.js","./package.json":"./package.json","./app/extend/agent":"./dist/app/extend/agent.js","./lib/strategy/all":"./dist/lib/strategy/all.js","./lib/load_schedule":"./dist/lib/load_schedule.js","./lib/strategy/base":"./dist/lib/strategy/base.js","./lib/strategy/timer":"./dist/lib/strategy/timer.js","./lib/schedule_worker":"./dist/lib/schedule_worker.js","./lib/strategy/worker":"./dist/lib/strategy/worker.js","./config/config.default":"./dist/config/config.default.js","./app/extend/application":"./dist/app/extend/application.js","./app/extend/application.unittest":"./dist/app/extend/application.unittest.js"},"scripts":{"typecheck":"tsgo --noEmit"},"_npmUser":{"name":"GitHub Actions","email":"npm-oidc-no-reply@github.com","trustedPublisher":{"id":"github","oidcConfigId":"oidc:dd577e2a-c446-420d-bdb2-c3865731bde3"}},"_resolved":"/tmp/1a504a154afd7c4c54872bf33f226681/eggjs-schedule-6.0.2-beta.7.tgz","_integrity":"sha512-ZOuzN6RIO4UNSpQa61HuMv4Asb/XSJbGCZmkUJUyfrZPgBBzuI8gRilWBTobeS7ztDHfCwXO2sjq6QJWP6nrfQ==","repository":{"url":"git+https://github.com/eggjs/egg.git","type":"git","directory":"plugins/schedule"},"_npmVersion":"11.9.0","description":"schedule plugin for egg, support corn job.","directories":{},"_nodeVersion":"24.14.0","dependencies":{"utility":"^2.5.0","is-type-of":"^2.2.0","cron-parser":"^4.9.0","humanize-ms":"^2.0.0","safe-timers":"^1.1.0","@eggjs/utils":"5.0.2-beta.7"},"publishConfig":{"access":"public"},"_hasShrinkwrap":false,"readmeFilename":"README.md","devDependencies":{"egg":"4.1.2-beta.7","@eggjs/bin":"8.0.2-beta.7","typescript":"^5.9.3","@eggjs/mock":"7.0.2-beta.7","@eggjs/tsconfig":"3.1.2-beta.7","@types/safe-timers":"^1.1.2"},"peerDependencies":{"egg":"4.1.2-beta.7"},"_npmOperationalInternal":{"tmp":"tmp/schedule_6.0.2-beta.7_1774925184911_0.1288648417263274","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":1774925185097,"_cnpm_publish_time":1774925185097,"dist-tags":{"beta":"6.0.2-beta.27","latest":"6.1.0","rc":"6.0.2-rc.1"}}