Node cron task not working after app running for a while (node-cron, cronr, timexe)

3.9k Views Asked by At

I am trying to leave a node application with a cron job running on my laptop and it seems to work if I start the app not long before the job has to actually run. What I mean by this is if, for example, I set a job to run at 2:05 pm and I start the app at 2 pm, it runs fine, but if I start the app at 10 am, I don't know why, the job doesn't run (but the app IS still running) which is weird.

Does anyone know if locking my macbook (not turning the machine off, of course) or having the app running for a long time (say more than 1-2 hours) does something with node or macOS does something that may be the culprit of my job not running even if the app is still running?

It's weird because if I start the app just a bit before the job needs to run, everything runs fine, it's like if having the app running for a long time makes the job not work, but the app still runs.

I'm really confused about this, hope I made myself clear.

The code, just in case:

const Cronr = require("cronr");
const fetch = require("node-fetch");
const job = new Cronr("* 58 18 1 * * *", () => {
  fetch("https://google.com")
   .then((r) => r.text())
   .then((r) => {
     console.log(r);
});
job.start()
3

There are 3 best solutions below

1
On BEST ANSWER

I finally found out it was because of the mac going to sleep when the display was off. Not sure what that does with programs running but I installed Amphetamine and made it so it doesn't go to sleep and it worked. Thanks everyone.

2
On

Here is a cronjob scheduled to run every minute:

("* * * * *")

first, check if this one is working fine.
And this is an example of a cronjob scheduled to run every night at 12:00:

("0 0 * * *")
0
On

Maybe its related with your system clock, in my case i usually use "normal cron" dependecy.

npm install cron

You can specify the time zone you want cron to check to execute the schedule

var job = new CronJob('5 14 * * *', function() {
  console.log('You will see this message every day at 2:05 pm');
}, null, true, 'America/Los_Angeles');
job.start();

Btw I leave you here a link to page to choose more easily your cron schedules: https://crontab.guru/

Hope, this helps you

PS: I had a lot of problems using other cron dependencies, and I allways came back to the this one.