Gathering detailed insights and metrics for @eggjs/schedule
Gathering detailed insights and metrics for @eggjs/schedule
Gathering detailed insights and metrics for @eggjs/schedule
Gathering detailed insights and metrics for @eggjs/schedule
npm install @eggjs/schedule
Typescript
Module System
Min. Node Version
Node Version
NPM Version
TypeScript (100%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
88 Stars
97 Commits
19 Forks
11 Watchers
4 Branches
30 Contributors
Updated on Apr 07, 2025
Latest Version
5.0.2
Package Id
@eggjs/schedule@5.0.2
Unpacked Size
130.86 kB
Size
27.30 kB
File Count
81
NPM Version
10.8.2
Node Version
20.18.1
Published on
Dec 20, 2024
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
A schedule plugin for egg, has been built-in plugin for egg enabled by default.
It's fully extendable for a developer and provides a simple built-in TimerStrategy.
Just add your job file to {baseDir}/app/schedule
.
1// {baseDir}/app/schedule/cleandb.ts 2import { Subscription } from 'egg'; 3 4export default class CleanDB extends Subscription { 5 /** 6 * @property {Object} schedule 7 * - {String} type - schedule type, `worker` or `all` or your custom types. 8 * - {String} [cron] - cron expression, see [below](#cron-style-scheduling) 9 * - {Object} [cronOptions] - cron options, see [cron-parser#options](https://github.com/harrisiirak/cron-parser#options) 10 * - {String | Number} [interval] - interval expression in millisecond or express explicitly like '1h'. see [below](#interval-style-scheduling) 11 * - {Boolean} [immediate] - To run a scheduler at startup 12 * - {Boolean} [disable] - whether to disable a scheduler, usually use in dynamic schedule 13 * - {Array} [env] - only enable scheduler when match env list 14 */ 15 static get schedule() { 16 return { 17 type: 'worker', 18 cron: '0 0 3 * * *', 19 // interval: '1h', 20 // immediate: true, 21 }; 22 } 23 24 async subscribe() { 25 await this.ctx.service.db.cleandb(); 26 } 27}
You can also use function simply like:
1import { EggContext } from 'egg'; 2 3export const schedule = { 4 type: 'worker', 5 cron: '0 0 3 * * *', 6 // interval: '1h', 7 // immediate: true, 8} 9 10export async function task(ctx: EggContext) { 11 await ctx.service.db.cleandb(); 12}
@eggjs/schedule
supports both cron-based scheduling and interval-based scheduling.
Schedule 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.
To 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.
The rule of thumbs is one job per file.
Task is a class which will be instantiated with every schedule, and a subscribe
method will be invoked.
You can get anonymous context with this.ctx
.
SCHEDULE
/__schedule?path=${schedulePath}&${schedule}
.To create a task, subscribe
can be a generator function or async function. For example:
1// A simple logger example 2import { Subscription } from 'egg'; 3 4export default class LoggerExample extends Subscription { 5 async subscribe() { 6 this.ctx.logger.info('Info about your task'); 7 } 8}
1// A real world example: wipe out your database. 2// Use it with caution. :) 3import { Subscription } from 'egg'; 4 5export default class CleanDB extends Subscription { 6 async subscribe() { 7 await this.ctx.service.db.cleandb(); 8 } 9}
schedule
is an object that contains one required property, type
, and optional properties, { cron, cronOptions, interval, immediate, disable, env }
.
Use cron-parser.
Note:
cron-parser
supportsecond
as optional that is not supported by linux crontab.
@hourly / @daily / @weekly / @monthly / @yearly
is also supported.
1* * * * * * 2┬ ┬ ┬ ┬ ┬ ┬ 3│ │ │ │ │ | 4│ │ │ │ │ └ day of week (0 - 7) (0 or 7 is Sun) 5│ │ │ │ └───── month (1 - 12) 6│ │ │ └────────── day of month (1 - 31) 7│ │ └─────────────── hour (0 - 23) 8│ └──────────────────── minute (0 - 59) 9└───────────────────────── second (0 - 59, optional)
Example:
1// To execute task every 3 hours 2export const schedule = { 3 type: 'worker', 4 cron: '0 0 */3 * * *', 5 cronOptions: { 6 // tz: 'Europe/Athens', 7 }, 8};
To use setInterval
, and support ms conversion style
Example:
1// To execute task every 3 hours 2export const schedule = { 3 type: 'worker', 4 interval: '3h', 5};
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.
Build-in support is:
worker
: will be executed in one random worker when a schedule runs.all
: will be executed in all workers when a schedule runs.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)
.
1// {baseDir}/agent.ts 2import { Agent } from 'egg'; 3 4export default (agent: Agent) => { 5 class CustomStrategy extends agent.ScheduleStrategy { 6 start() { 7 // such as mq / redis subscribe 8 agent.notify.subscribe('remote_task', data => { 9 this.sendOne(data); 10 }); 11 } 12 } 13 14 agent.schedule.use('custom', CustomStrategy); 15}
Then you could use it to defined your job:
1// {baseDir}/app/schedule/other.ts 2import { Subscription } from 'egg'; 3 4export default class ClusterTask extends Subscription { 5 static get schedule() { 6 return { 7 type: 'custom', 8 }; 9 } 10 11 async subscribe(data) { 12 console.log('got custom data:', data); 13 await this.ctx.service.someTask.run(); 14 } 15}
1// {baseDir}/app/schedule/sync.ts 2import { Application } from 'egg'; 3 4export default (app: Application) => { 5 class SyncTask extends app.Subscription { 6 static get schedule() { 7 return { 8 interval: 10000, 9 type: 'worker', 10 // only start task when hostname match 11 disable: require('os').hostname() !== app.config.sync.hostname, 12 // only start task at prod mode 13 env: [ 'prod' ], 14 }; 15 } 16 17 async subscribe() { 18 await this.ctx.sync(); 19 } 20 } 21 22 return SyncTask; 23}
See ${appInfo.root}/logs/{app_name}/egg-schedule.log
which provided by config.customLogger.scheduleLogger.
1// config/config.default.ts 2import { EggAppConfig } from 'egg'; 3 4export default { 5 customLogger: { 6 scheduleLogger: { 7 // consoleLevel: 'NONE', 8 // file: path.join(appInfo.root, 'logs', appInfo.name, 'egg-schedule.log'), 9 }, 10 }, 11} as Partial<EggAppConfig>;
If you want to add additional schedule directories, you can use this config.
1// config/config.default.ts 2import { EggAppConfig } from 'egg'; 3 4export default { 5 schedule: { 6 directory: [ 7 'path/to/otherSchedule', 8 ], 9 }, 10} as Partial<EggAppConfig>;
app.runSchedule(scheduleName)
is provided by @eggjs/schedule
plugin only for test purpose.
Example:
1it('test a schedule task', async () => { 2 // get app instance 3 await app.runSchedule('clean_cache'); 4});
Please open an issue here.
Made with contributors-img.
No vulnerabilities found.
No security vulnerabilities found.