node.jsnode-cron

Cron is running 2 times node-cron


I installed node-cron library and configured 2 crons in the same file to run at different intervals. The first cron runs every 45 seconds and the second cron runs every 60 seconds, it works perfectly. The problem happens when the 60-second cron is run, automatically the 45-second cron is also run again (notice that the difference is 15 seconds). Why does this happen?

const cron = require('node-cron'); 

cron.schedule('*/45 * * * * *', async () => { 
   console.log('running 45 seconds')
})

cron.schedule('*/60 * * * * *', async () => { 
   console.log('running 60 seconds')
})

Solution

  • Cron will run this at "every 45th second, of every minute...".

    Starts at 0 seconds, then at 45 seconds. Starts at 0 seconds, then at 45 seconds.

    This will be noticeable whenever the */x interval isn't divisible by the parent time unit (seconds in a minute, minutes in an hour etc).

    For example, */17 * * * * *

    2021-08-17T23:07:00.230Z running */17 seconds
    2021-08-17T23:07:17.273Z running */17 seconds
    2021-08-17T23:07:34.302Z running */17 seconds
    2021-08-17T23:07:51.344Z running */17 seconds
    2021-08-17T23:08:00.374Z running */17 seconds
    2021-08-17T23:08:17.424Z running */17 seconds
    2021-08-17T23:08:34.467Z running */17 seconds
    2021-08-17T23:08:51.494Z running */17 seconds
    2021-08-17T23:09:00.525Z running */17 seconds
    2021-08-17T23:09:17.564Z running */17 seconds
    

    To run something on a 45 second timer via cron, you probably need a task every 15 seconds then some logic to check if the previous run was >= 45 seconds ago.