npm cron in different file nodejs/express

Viewed 101

I'm making use of the npm cron package, I'm trying to put jobs in different files so I can require them throughout my whole application and access them. An example is (cron.js):

const CronJob = require("cron").CronJob;
const { otherFunction } = require("../services/service");

const job = new CronJob(
  `*/30 * * * * *`,
  () => {}
);

module.exports.initializeCron = (io) => {
  job.fireOnTick = () => {
    otherFunction(io);
  };

  return job;
};

module.exports.cron = job;

However this job needs the io parameter (socketio) to function which is only available in my app.js at the moment. In app.js I do the following:

const io = require("socket.io")(http, {
  cors: {
    origin: "http://localhost:3000",
    methods: ["GET", "POST"],
    credentials: true,
  },
});
const job = require("./crons/job").initializeCron(io);

job.start();

So I call the initialize function with the io parameter within my app.js which assigns the cron function. This seems to work but I rather find it a bit weird to first instantiate the object and then change the cron behaviour, is there a cleaner way?

0 Answers
Related