Search code examples
javascriptmeteorcronnode-fetchnode-schedule

Issue: cron routine launching several times after Meteor server start


I'm currently working on a Meteor app. Several cron routine are launched using the npm package node-schedule. My problem is that after the initial launch of the meteor server (using the command line 'meteor yarn start:dev'), the routine is executed many times at once, then every minute as expected. Obviously this is causing some problems related to the async nature of these routines.

My hypothesis: since the initial built takes about 3 minutes and the routine is scheduled every minute, I figured that the scheduler might be initialised at the beginning of the build process somehow, thus resulting in multiple launches when the server is actually ready.

Some example code to clear the situation:

const schedule = require('node-schedule');
const fetch = require('node-fetch');

schedule.scheduleJob('*/1 * * * *', // cron pattern for every minute
function () {
  fetch("whatever/my/routine/route", {
    headers: { 'Content-type': 'application/json' },
    method: 'GET'
  })
});

I've already made some research on how to access the meteor server status inside the routine code in order to execute only when the server is fully operational, but found nothing.

Anything that could help is welcome, even a workaround. And keep in mind hat my hypothesis might be completely wrong.


Solution

  • Try wrapping your scheduler code in a Meteor.startup callback

    Meteor.startup(() => {
      schedule.scheduleJob('*/1 * * * *', // cron pattern for every minute
        function () {
          fetch("whatever/my/routine/route", {
            headers: { 'Content-type': 'application/json' },
            method: 'GET'
          });
        });
    });