How to program a function to run every day with NodeJS and Generators?

advertisements

I need a function to be called every day at a given hour with generators (yields), doing my search I've found out two node modules that enable me to do this, one is node-schedule and the other one is node-cron

Node-cron does not seems to support generators

Node-schedule should have the support but it seems to not work as pointed out here: issue #325

To be more clear about what I'm trying to accomplish I attach the same code the issue #325 has:

const date = momemt().add(1, 's'); // 1 second after now.
schedule.scheduleJob('taksid', date, function*(){
    console.log('Hi');
    const result = yield Message.findAll();
    console.log('Result: ' + result);
});

As specified in the issue, 'Hi' gets printed out while 'result' does not.

I'm not able to find out a way to schedule a function with generators, if some of you know how to do it that would be great! Thank in advance guys


Came across the same problem "How to schedule a functions to run everyday with NodeJS and Generators?" on friday and just now after the weekend I came up with a solution. Maybe it might solve your problem as well.

The first step is to create a shell file. I'm using Windows 10 so you might have to adapt it if using Mac.

#!/bin/bash
echo " # Starting Scraper ..."
  pkill -f "node fileWithYieldToBeScheduled.js"
  sleep 1
  node fileWithYieldToBeScheduled.js -D
  status=$?
  if [ $status -ne 0 ]; then
      echo "Failed to start node: $status"
      exit $status
    else
      echo "Success"
  fi

Explanation: Name this "myFancyFileToScheduleYields.sh" and place it in your root directory. Next create a "scheduleYields.js" with the following content.

const childProcess = require('child_process');
var cron = require('node-cron');

/**
 * Your task to be scheduled.
 */
const startFileWithYields= function () {
  childProcess.exec(__dirname + "/myFancyFileToScheduleYields.sh", function (err, stdout, stderr) {
    if (err) {
      return console.log(stderr);
    }

    console.log(stdout);
  });
}

cron.schedule('*/5 * * * *', function () {
  startFileWithYields();
});

Finally do "node scheduleYields.js" and observe how the magic happens.

This will run the task every 5 Minute according to the documentation. Now go and adapt it to your usecase and give feedback if it worked.

I even tested this with Docker and and works as well :)