Node.js setInterval() stops executing after 25 days
Asked Answered
A

3

11

In my Node.js application, I use setInterval() to run a specific function every 1 hour. The function is executed properly for about 25 days, then the timer stops firing.

25 days seems awfully close to Node.js's TIMEOUT_MAX (2^31 milliseconds ≈ 25 days), but I don't really see why setInterval() should stop executing after that time.

Update:

I think this may have been caused by the following bug in Node.js: setInterval callback function unexpected halt #22149

Adjudicate answered 14/8, 2018 at 6:51 Comment(11)
Have you tried using a recursive setTimeout instead?Mashhad
What is your code?Anatolia
#51826766Anatolia
Could you use something like cron / schtasks / some other OS-level scheduler instead?Ioab
@Anatolia thanks, that indeed seems to be the same problem.Adjudicate
@Ioab I could use cron, although that would require some additional logic in my application. I was hoping there may be some easy fix for setInterval().Adjudicate
@Mashhad I haven't, but the question linked by @Anatolia suggests that setTimeout has the exact same problem.Adjudicate
Does anything else in your node.js process remain active and working? Or is the setInterval() the only thing it's doing. It could be that your whole process becomes unresponsive perhaps because of a memory or resource leak.Overburden
@Overburden the process is fine, only the timer stops working. I think this may be a bug in Node.js, I updated my question.Adjudicate
maybe you can use node-cron, too.Agace
@Agace I don't know about node-cron, but we were using node-schedule before and had the exact same problem. Anyway, it seems it's been fixed in Node.js now.Adjudicate
A
6

It seems the bug (#22149) has been fixed in Node.js 10.9.0.

It may be also worth noting that this bug seems to be influencing both setInterval() and setTimeout() (as reported here), so the workaround with setTimeout() in the callback function wouldn't work.

Adjudicate answered 16/8, 2018 at 6:2 Comment(0)
P
1

After reading the issue in github, I think they will fix it in the next release. If you need to work around before that, you can try recursive timeout instead. Checkout my code:

function doSomething() {
    console.log('test');
}

function doSomethingInterval() {
   doSomething();
   setTimeout(doSomethingInterval, 1000);
}

doSomethingInterval();
Prado answered 14/8, 2018 at 8:15 Comment(0)
T
0

It's a known bug. Your easiest workaround is to use setTimeout instead, and then in your callback function call another setTimeout.

Tomb answered 14/8, 2018 at 8:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.