Vinicius Aquino
Vinicius Aquino

Reputation: 737

When a cron job is executed and there is already a cron running, are they running simultaneously?

my question may seem a little strange but I will try to explain, I have a cron job that executes a function, inside this function there is a loop that executes other functions, this cron is called every 1 minute, so far so good . The problem is that this function called by cron takes more than 1 minute to finish because of the loop, when the next minute the cron runs, it will call this function again and it will cancel the previous task or it will run both at the same time? I don't know if I could explain it in a good way.

 /*---------- Cron ----------*/
cron.schedule('*/60 * * * * *', async () => {
  this.analyze();

  // this function takes about 2-3 minutes to finish the loop.
})

Upvotes: 1

Views: 2922

Answers (2)

Dinesh
Dinesh

Reputation: 104

I have some sample code(not tested), hope you can get some idea from it:

var counter =0
var counterArray = []

async function asyncAnalyze(){
           
         counter = counter+1
         counterArray.push(counter)

for(let i=0;i<counterArray.length;i++){
    const eachResult = await analyze();
console.log(‘Counter: ’, i, ‘ Result: ’, eachResult)
counter = counter - 1       
}
return ;
}

cron.schedule('*/60 * * * * *', async () => {
      this.asyncAnalyze()
})

async function analyze(){ }

Upvotes: 0

Jameson_uk
Jameson_uk

Reputation: 487

Yes. CRON is just a scheduler. It will run the command according to the schedule regardless.

There are plenty of ways of preventing multiple runs but these need to be manually implemented.

Several people have done this already like https://github.com/kelektiv/node-cron/issues/347

Upvotes: 2

Related Questions