Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could nodejs app execute the task at the specific time reliably?

I want to execute the task at the specific time in nodejs app.
So I've written the source like the below using Timer.

 var _to_execute_time = 1571221163000;   //The timestamp to execute the task.  
 var _current_timestamp = Date.now();   //The current timestamp.  
//Scheduling the task using setTimeout();

 setTimeout(task_function,  _to_execute_time - _current_timestamp);  

The problem is that setTimeout() is canceled if system reboots before executing the task.
How could I fix this issue and run the task reliably?

like image 577
Andrew Li Avatar asked Mar 27 '26 18:03

Andrew Li


1 Answers

You can use node-cron. The crone will run on a specified time.

The npm package you can use is node-cron.

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

cron.schedule('* * * * *', () => {
  console.log('running a task every minute');
});

OR

cron.schedule('0 11 * * *', () => {
  console.log('running a task at 11:00 AM');
});

Allowed fields for setting the time:

 # ┌────────────── second (optional)
 # │ ┌──────────── minute
 # │ │ ┌────────── hour
 # │ │ │ ┌──────── day of month
 # │ │ │ │ ┌────── month
 # │ │ │ │ │ ┌──── day of week
 # │ │ │ │ │ │
 # │ │ │ │ │ │
 # * * * * * *
like image 140
Surjeet Bhadauriya Avatar answered Mar 29 '26 06:03

Surjeet Bhadauriya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!