Skip to content

Commit be8e51b

Browse files
committed
fix: only update job state fields during job processing
this improves performance
1 parent e2cacb5 commit be8e51b

File tree

3 files changed

+25
-3
lines changed

3 files changed

+25
-3
lines changed

src/Job.ts

+4-3
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,8 @@ export class Job<DATA = unknown | void> {
282282
}
283283
this.attrs.lockedAt = new Date();
284284
this.attrs.progress = progress;
285-
await this.save();
285+
286+
await this.agenda.db.saveJobState(this);
286287
}
287288

288289
private computeNextRunAt() {
@@ -326,7 +327,7 @@ export class Job<DATA = unknown | void> {
326327
this.attrs.lastRunAt.toISOString()
327328
);
328329
this.computeNextRunAt();
329-
await this.save();
330+
await this.agenda.db.saveJobState(this);
330331

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

382383
this.agenda.emit('complete', this);

src/JobDbRepository.ts

+19
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,25 @@ export class JobDbRepository {
243243
return job;
244244
}
245245

246+
async saveJobState(job: Job<any>): Promise<void> {
247+
await this.collection.updateOne(
248+
{ _id: job.attrs._id },
249+
{
250+
$set: {
251+
lockedAt: job.attrs.lockedAt,
252+
nextRunAt: (job.attrs.nextRunAt && new Date(job.attrs.nextRunAt)) || undefined,
253+
lastRunAt: (job.attrs.lastRunAt && new Date(job.attrs.lastRunAt)) || undefined,
254+
progress: job.attrs.progress,
255+
failReason: job.attrs.failReason,
256+
failCount: job.attrs.failCount,
257+
failedAt: job.attrs.failedAt && new Date(job.attrs.failedAt),
258+
lastFinishedAt:
259+
(job.attrs.lastFinishedAt && new Date(job.attrs.lastFinishedAt)) || undefined
260+
}
261+
}
262+
);
263+
}
264+
246265
/**
247266
* Save the properties on a job to MongoDB
248267
* @name Agenda#saveJob

test/agenda.test.ts

+2
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,8 @@ describe('Agenda', () => {
318318
.schedule('now')
319319
.save();
320320

321+
await delay(100);
322+
321323
const job2 = await globalAgenda
322324
.create('unique job', {
323325
type: 'active',

0 commit comments

Comments
 (0)