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

Viewed 68

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?

2 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
 # │ │ │ │ │ │
 # │ │ │ │ │ │
 # * * * * * *

I would recommend to use node-schedule to do the task, it accepts cron format. you can schedule at task at a particular time or a repetitions of it

var j = schedule.scheduleJob('0 1 * * *', function(fireDate){ console.log('This job was supposed to run at ' + fireDate + ', but actually ran at ' + new Date()); });

https://www.npmjs.com/package/node-schedule

Related