kelektiv / node-cron

Cron for NodeJS.
MIT License
8.41k stars 621 forks source link

Job scheduled with setTime throws error instead of running #739

Closed lpgera closed 11 months ago

lpgera commented 11 months ago

Description

When I reschedule a job to a specific date using the job.setTime(new CronTime(startDate)) function, the job throws an error at the scheduled time instead of executing.

Expected Behavior

I expect the job to run at startDate.

Actual Behavior

I'm getting the following error:

node_modules/cron/dist/time.js:93
                throw new Error('WARNING: Date in past. Will never be fired.');
                ^

Error: WARNING: Date in past. Will never be fired.

Possible Fix

No response

Steps to Reproduce

// create job with a default schedule
const job = new CronJob(
  '0 0 20 * * *',
  () => console.log('onTick')
)

// re-schedule for 5 seconds from now
const startDate = new Date(Date.now() + 5000)
job.setTime(new CronTime(startDate))
job.start()

console.log('current date:', new Date())
console.log('start date:', startDate)

Context

This used to be working properly in earlier versions of the library.

Your Environment

sheerlox commented 11 months ago

thanks for reporting on this issue @lpgera!

after a bit of debugging, turns out this bug is due to not updating the internal runOnce property if setTime() is passed an actual date: image

so the callback is actually called once, but right after this it tries to execute again, causing this error.

I'm preparing a PR with the fix!

ncb000gt commented 11 months ago

:tada: This issue has been resolved in version 3.1.4 :tada:

The release is available on:

Your semantic-release bot :package::rocket: