Skip to content

Commit

Permalink
feat: run a scheduler only once at startup (#33)
Browse files Browse the repository at this point in the history
  • Loading branch information
zhennann authored and atian25 committed Nov 16, 2017
1 parent 83fd40a commit 69a588e
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 4 deletions.
5 changes: 2 additions & 3 deletions lib/timer.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
const parser = require('cron-parser');
const ms = require('humanize-ms');
const safetimers = require('safe-timers');
const assert = require('assert');

class Timer {
constructor(agent) {
Expand All @@ -19,9 +20,7 @@ class Timer {
*/
handler(key, schedule, listener) {
const { interval, cron, cronOptions, immediate } = schedule;
if (!interval && !cron) {
throw new Error('[egg-schedule] schedule.interval or schedule.cron must be present');
}
assert(interval || cron || immediate, '[egg-schedule] schedule.interval or schedule.cron or schedule.immediate must be present');

if (interval) {
const tid = this.safeInterval(listener, ms(interval));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
'use strict';

exports.schedule = {
type: 'worker',
immediate: true,
};

exports.task = async function(ctx) {
ctx.logger.info('immediate-onlyonce');
};
3 changes: 3 additions & 0 deletions test/fixtures/immediate-onlyonce/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"name": "immediate-onlyonce"
}
11 changes: 10 additions & 1 deletion test/schedule.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,15 @@ describe('test/schedule.test.js', () => {
assert(contains(log, 'immediate-interval') >= 2);
assert(contains(log, 'immediate-cron') >= 2);
});

it('should support immediate-onlyonce', async () => {
app = mm.cluster({ baseDir: 'immediate-onlyonce', workers: 2 });
await app.ready();
await sleep(1000);
const log = getLogContent('immediate-onlyonce');
// console.log(log);
assert(contains(log, 'immediate-onlyonce') === 1);
});
});

describe('schedule type all', () => {
Expand Down Expand Up @@ -157,7 +166,7 @@ describe('test/schedule.test.js', () => {
app = mm.cluster({ baseDir: 'scheduleError', workers: 2 });
await app.ready();
await sleep(1000);
assert(/\[egg-schedule\] schedule\.interval or schedule\.cron must be present/.test(getErrorLogContent('scheduleError')));
assert(/\[egg-schedule\] schedule\.interval or schedule\.cron or schedule\.immediate must be present/.test(getErrorLogContent('scheduleError')));
});
});

Expand Down

0 comments on commit 69a588e

Please sign in to comment.