Skip to content

Commit

Permalink
fix: schedule should execute after app ready (#60)
Browse files Browse the repository at this point in the history
* fix: schedule should execute after app ready
  • Loading branch information
killagu authored Mar 6, 2024
1 parent e1b9327 commit bf01a49
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 26 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/nodejs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,4 @@ jobs:
uses: artusjs/github-actions/.github/workflows/node-test.yml@v1
with:
os: 'ubuntu-latest'
version: '14, 16, 18'
version: '14, 16, 18, 20'
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ run/

test/fixtures/symlink/runDir/app/schedule/realFile.js
test/fixtures/symlink/runDir/app/schedule/tsRealFile.ts
package-lock.json
54 changes: 29 additions & 25 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@ module.exports = app => {
}

// register schedule event
app.messenger.on('egg-schedule', info => {
app.messenger.on('egg-schedule', async info => {
const { id, key } = info;
logger.debug(`[Job#${id}] ${key} await app ready`);
await app.ready();
const schedule = scheduleWorker.scheduleItems[key];

logger.debug(`[Job#${id}] ${key} task received by app`);

if (!schedule) {
Expand All @@ -43,30 +44,33 @@ module.exports = app => {

const start = Date.now();

// execute
return app.ctxStorage.run(ctx, () => {
return schedule.task(ctx, ...info.args)
.catch(err => {
return is.error(err) ? err : new Error(err);
})
.then(err => {
const success = !is.error(err);
const rt = Date.now() - start;

const msg = `[Job#${id}] ${key} execute ${success ? 'succeed' : 'failed'}, used ${rt}ms.`;
logger[success ? 'info' : 'error'](msg, success ? '' : err);

Object.assign(info, {
success,
workerId: process.pid,
rt,
message: err && err.message,
});

// notify agent job finish
app.messenger.sendToAgent('egg-schedule', info);
});
let success;
let e;
try {
// execute
await app.ctxStorage.run(ctx, async () => {
return await schedule.task(ctx, ...info.args);
});
success = true;
} catch (err) {
success = false;
e = is.error(err) ? err : new Error(err);
}

const rt = Date.now() - start;

const msg = `[Job#${id}] ${key} execute ${success ? 'succeed' : 'failed'}, used ${rt}ms.`;
logger[success ? 'info' : 'error'](msg, success ? '' : e);

Object.assign(info, {
success,
workerId: process.pid,
rt,
message: e && e.message,
});

// notify agent job finish
app.messenger.sendToAgent('egg-schedule', info);
});

// for test purpose
Expand Down

0 comments on commit bf01a49

Please sign in to comment.