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

Moorglade
  • 316
  • 2
  • 8
  • Have you tried using a recursive `setTimeout` instead? – CertainPerformance Aug 14 '18 at 06:52
  • 2
    What is your code? – user202729 Aug 14 '18 at 06:54
  • https://stackoverflow.com/questions/51826266/nodejs-settimout-loop-stopped-after-many-weeks-of-iterations/51826893 – user202729 Aug 14 '18 at 06:56
  • 1
    Could you use something like `cron` / `schtasks` / some other OS-level scheduler instead? – Phil Aug 14 '18 at 06:57
  • @user202729 thanks, that indeed seems to be the same problem. – Moorglade Aug 14 '18 at 07:06
  • @Phil 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()`. – Moorglade Aug 14 '18 at 07:09
  • @CertainPerformance I haven't, but the question linked by @user202729 suggests that `setTimeout` has the exact same problem. – Moorglade Aug 14 '18 at 07:09
  • 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. – jfriend00 Aug 14 '18 at 07:22
  • @jfriend00 the process is fine, only the timer stops working. I think this may be a bug in Node.js, I updated my question. – Moorglade Aug 14 '18 at 07:41
  • maybe you can use [node-cron](https://github.com/kelektiv/node-cron), too. – NoobTW Aug 14 '18 at 09:10
  • 1
    @NoobTW 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. – Moorglade Aug 16 '18 at 06:07

3 Answers3

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.

Moorglade
  • 316
  • 2
  • 8
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();
Dat Tran
  • 1,576
  • 1
  • 12
  • 16
0

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

Prodigle
  • 1,757
  • 12
  • 23