Skip to content

Commit

Permalink
fix: only update job state fields during job processing
Browse files Browse the repository at this point in the history
this improves performance
  • Loading branch information
simllll committed Dec 10, 2021
1 parent e2cacb5 commit be8e51b
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/Job.ts
Expand Up @@ -282,7 +282,8 @@ export class Job<DATA = unknown | void> {
}
this.attrs.lockedAt = new Date();
this.attrs.progress = progress;
await this.save();

await this.agenda.db.saveJobState(this);
}

private computeNextRunAt() {
Expand Down Expand Up @@ -326,7 +327,7 @@ export class Job<DATA = unknown | void> {
this.attrs.lastRunAt.toISOString()
);
this.computeNextRunAt();
await this.save();
await this.agenda.db.saveJobState(this);

try {
this.agenda.emit('start', this);
Expand Down Expand Up @@ -376,7 +377,7 @@ export class Job<DATA = unknown | void> {
log('[%s:%s] has failed [%s]', this.attrs.name, this.attrs._id, error.message);
} finally {
this.attrs.lockedAt = undefined;
await this.save();
await this.agenda.db.saveJobState(this);
log('[%s:%s] was saved successfully to MongoDB', this.attrs.name, this.attrs._id);

this.agenda.emit('complete', this);
Expand Down
19 changes: 19 additions & 0 deletions src/JobDbRepository.ts
Expand Up @@ -243,6 +243,25 @@ export class JobDbRepository {
return job;
}

async saveJobState(job: Job<any>): Promise<void> {
await this.collection.updateOne(
{ _id: job.attrs._id },
{
$set: {
lockedAt: job.attrs.lockedAt,
nextRunAt: (job.attrs.nextRunAt && new Date(job.attrs.nextRunAt)) || undefined,
lastRunAt: (job.attrs.lastRunAt && new Date(job.attrs.lastRunAt)) || undefined,
progress: job.attrs.progress,
failReason: job.attrs.failReason,
failCount: job.attrs.failCount,
failedAt: job.attrs.failedAt && new Date(job.attrs.failedAt),
lastFinishedAt:
(job.attrs.lastFinishedAt && new Date(job.attrs.lastFinishedAt)) || undefined
}
}
);
}

/**
* Save the properties on a job to MongoDB
* @name Agenda#saveJob
Expand Down
2 changes: 2 additions & 0 deletions test/agenda.test.ts
Expand Up @@ -318,6 +318,8 @@ describe('Agenda', () => {
.schedule('now')
.save();

await delay(100);

const job2 = await globalAgenda
.create('unique job', {
type: 'active',
Expand Down

0 comments on commit be8e51b

Please sign in to comment.