Skip to content

fix(cron): do not resurrect a deleted job after its initialDelay elapses - #2344

Merged
kamilmysliwiec merged 1 commit into
nestjs:masterfrom
chuanghiduoc:fix/cron-initial-delay-resurrection
Sep 14, 2026
Merged

kamilmysliwiec merged 1 commit into
nestjs:masterfrom
chuanghiduoc:fix/cron-initial-delay-resurrection

Conversation

@chuanghiduoc

Copy link
Copy Markdown
Contributor

Problem

A cron job declared with initialDelay keeps a plain setTimeout whose callback only checked doesExist('cron', name) before calling cronJob.start(). Two consequences:

  1. If the job is deleted while the delay is pending, the captured reference is still started once the delay elapses — the deleted job runs forever.
  2. If a different job is registered under the same name in that window, both the old and the new job run in parallel.

Reproduction (new e2e test in this PR, fails without the fix):

registry.deleteCronJob('RESURRECT_ME');          // during initialDelay window
registry.addCronJob('RESURRECT_ME', replacement); // same name, new job
vi.advanceTimersByTime(7000);                     // past the 5s delay
// old job ticked twice; expected zero times

Fix

The timer now starts the job only when the registry still maps that name to exactly the same CronJob instance:

if (
  this.schedulerRegistry.doesExist('cron', key) &&
  this.schedulerRegistry.getCronJob(key) === cronJob
) {
  cronJob.start();
}

The doesExist guard stays so deleting a delayed job without re-registering does not throw from the timer callback.

Testing

  • new test: tests/e2e/cron-initial-delay.spec.ts
  • full suite: 6 files / 53 tests passing

A cron job with initialDelay is started by a plain setTimeout callback
that only checked whether the job name still exists in the registry.
If the job was deleted while the delay was pending, the captured job
reference was started anyway; and if a different job had been registered
under the same name in the meantime, both ran in parallel forever.

The timer now only starts the job when the registry still holds exactly
the same job instance under that name.
@kamilmysliwiec
kamilmysliwiec merged commit cdbaa32 into nestjs:master Sep 14, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants