0

I'm trying to execute once a cron job in nodejs with express, with the follow code:

const cron = require("node-cron");
const EventEmitter = require("events");
const event = new EventEmitter();
...
let task: any = {};
const taskName = newFileName.split(".")[0];
task[taskName] = cron.schedule(
  `0 */${process.env.TIME} * * *`,
  async () => {
    await deleteFile();
    event.emit("JOB_COMPLETED", taskName);
  }
);
event.on("JOB_COMPLETED", (completedTaskName: string) => {
  task[completedTaskName].stop();
});
...

the Idea is that you can change the time that the cron will run with the env vars,

testing my code, the problem is:

using TIME= 1

with 0 */1 * * *, the code is execute the next hour, I mean if time is 17:55 the code is executed at 18:00 and not at 18:55 (one hour later)

What is the correct setting to run "TIME" hours after the cronjob was created and started?

ex:

TIME = 1


if start at | run at

2:33 | 2:33 + TIME = 3:33

13:01 | 13:01 + TIME = 14: 01

20:15 | 20:15 + TIME = 21:15

TIME = 3


if start at | run at

2:33 | 2:33 + TIME = 5:33

13:01 | 13:01 + TIME = 16: 01

20:15 | 20:15 + TIME = 23:15

andres martinez
  • 994
  • 2
  • 10
  • 21
  • `0 */${process.env.TIME} * * *` instead of doing this, why not you are putting this whole string into env variable. For example store `55 * * * *` this complete string into env variable if you want to run your cron on every 55th minutes. – Munam Tariq Mar 23 '23 at 22:17
  • @MunamTariq, ok but whats the configuration for X hours after cron was created/started – andres martinez Mar 23 '23 at 22:55

1 Answers1

0

Solved

getting the current minutues with date.getMinutes() to know after next hour how many minutos it needs to complete one hour:

var date = new Date;
...
cron.schedule(
      `${date.getMinutes()} */${process.env.TIME} * * *`,
      async () => {
...
andres martinez
  • 994
  • 2
  • 10
  • 21