Skip to content

Commit

Permalink
fix: run once when actual date is given to setTime (kelektiv#740)
Browse files Browse the repository at this point in the history
  • Loading branch information
sheerlox committed Oct 24, 2023
1 parent 6d94742 commit ee54dd5
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 8 deletions.
9 changes: 3 additions & 6 deletions src/job.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ export class CronJob<OC extends CronOnCompleteCommand | null = null, C = null> {
running = false;
unrefTimeout = false;
lastExecution: Date | null = null;
runOnce = false;
context: CronContext<C>;
onComplete?: WithOnComplete<OC> extends true
? CronOnCompleteCallback
Expand Down Expand Up @@ -84,10 +83,6 @@ export class CronJob<OC extends CronOnCompleteCommand | null = null, C = null> {
) as WithOnComplete<OC> extends true ? CronOnCompleteCallback : undefined;
}

if (this.cronTime.realDate) {
this.runOnce = true;
}

this.addCallback(this._fnWrap(onTick));

if (runOnInit) {
Expand Down Expand Up @@ -181,7 +176,9 @@ export class CronJob<OC extends CronOnCompleteCommand | null = null, C = null> {
}
const wasRunning = this.running;
this.stop();

this.cronTime = time;

if (wasRunning) this.start();
}

Expand Down Expand Up @@ -258,7 +255,7 @@ export class CronJob<OC extends CronOnCompleteCommand | null = null, C = null> {
this.running = false;

// start before calling back so the callbacks have the ability to stop the cron job
if (!this.runOnce) {
if (!this.cronTime.realDate) {
this.start();
}

Expand Down
4 changes: 2 additions & 2 deletions src/time.ts
Original file line number Diff line number Diff line change
Expand Up @@ -684,7 +684,7 @@ export class CronTime {
return true;
}

/*
/**
* Parse the cron syntax into something useful for selecting the next execution time.
*
* Algorithm:
Expand Down Expand Up @@ -733,7 +733,7 @@ export class CronTime {
}
}

/*
/**
* Parse individual field from the cron syntax provided.
*
* Algorithm:
Expand Down
23 changes: 23 additions & 0 deletions tests/cron.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1080,6 +1080,29 @@ describe('cron', () => {
job.stop();
expect(callback).toHaveBeenCalledTimes(1);
});

it('should create recurring job, setTime with actual date, start and run once (#739)', () => {
const callback = jest.fn();
const clock = sinon.useFakeTimers();

const job = new CronJob('0 0 20 * * *', callback);

const startDate = new Date(Date.now() + 5000);
job.setTime(new CronTime(startDate));

job.start();

clock.tick(5000);

expect(callback).toHaveBeenCalledTimes(1);

clock.tick(60000);

clock.restore();

expect(callback).toHaveBeenCalledTimes(1);
expect(job.running).toBe(false);
});
});

describe('nextDate(s)', () => {
Expand Down

0 comments on commit ee54dd5

Please sign in to comment.