Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs Run code at exactly time once

Tags:

node.js

I want to run my process at specific time but just one time. Should I use cron job, execute then stop job or use setTimeout ? Which 's better ?

Update : I found it in node-cron module. I think it's better than using setTimeout.

Another example with Date

var CronJob = require('cron').CronJob;
var job = new CronJob(new Date(), function(){
 //runs once at the specified date.
}, function () {
 // This function is executed when the job stops
},
true /* Start the job right now */,
timeZone /* Time zone of this job. */

);

like image 900
Windranger Avatar asked Nov 14 '25 16:11

Windranger


2 Answers

Check out node-schedule package. According to the docs, you can schedule a function at an exact date.

This is the docs example of scheduling an event at 5:30am on December 21, 2012...

var schedule = require('node-schedule');
var date = new Date(2012, 11, 21, 5, 30, 0);

var j = schedule.scheduleJob(date, function(){
  console.log('The world is going to end today.');
});

If need be, you can cancel a job as well

j.cancel();
like image 58
bizzurnzz Avatar answered Nov 17 '25 08:11

bizzurnzz


Try this with cron if not work try with node-cron.

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

const todayMoment = moment().format();
const today = new Date();

function formatDate(date) {
/* take care of the values:
   second: 0-59 same for javascript
   minute: 0-59 same for javascript
   hour: 0-23 same for javascript
   day of month: 1-31 same for javascript
   month: 1-12 (or names) is not the same for javascript 0-11
   day of week: 0-7 (or names, 0 or 7 are sunday) same for javascript
   */
  return `${date.getSeconds()} ${date.getMinutes() + 1} ${date.getHours()} ${date.getDate()} ${date.getMonth() + 1} ${date.getDay()}`;
}

function formatDateMoment(momentDate) {
  const date = new Date(momentDate);

  return `${date.getSeconds()} ${date.getMinutes() + 1} ${date.getHours()} ${date.getDate()} ${date.getMonth() + 1} ${date.getDay()}`;
  // or return moment(momentDate).format('ss mm HH DD MM dddd');
}

function runJob(data) {
  // or                     formatDateMoment
  const job = cron.schedule(formatDate(data), () => {
    doSomething();
  });

  function doSomething() {
    // my code

    // stop task or job
    job.stop();
  }
}
//    todayMoment
runJob(today);
like image 26
Milianor Avatar answered Nov 17 '25 08:11

Milianor