admin管理员组文章数量:1328358
I set quite a few server-side timeouts with setTimeout and setInterval for each connected user that can last for 10-30 seconds. If the Node.js instance restarts in the middle of one of these timeouts, they are obviously all cleared on restart, which can cause some issues for these users. How would I go about persisting these timeouts, or are there any modules that already help with this?
I set quite a few server-side timeouts with setTimeout and setInterval for each connected user that can last for 10-30 seconds. If the Node.js instance restarts in the middle of one of these timeouts, they are obviously all cleared on restart, which can cause some issues for these users. How would I go about persisting these timeouts, or are there any modules that already help with this?
Share Improve this question asked Jul 12, 2012 at 14:54 James SimpsonJames Simpson 13.7k26 gold badges85 silver badges111 bronze badges 5- can't you use node cron for this? – albertjan Commented Jul 12, 2012 at 18:43
- 1 How so? These are not cron jobs I'm setting up, they are 10-30 second timeouts based on user interactions with the app. – James Simpson Commented Jul 12, 2012 at 18:53
- You could use beanstalkd for that. It can even persist. – Alfred Commented Nov 28, 2012 at 23:22
- @JamesSimpson Did you get anywhere with this? – scanales Commented Dec 12, 2012 at 23:11
- Yes, I ended up doing something similar to Loc Nguyen's suggestion (looks like I forgot to mark it as the answer). This solution has worked very well, and it has been in production since August without issue. – James Simpson Commented Dec 19, 2012 at 18:41
2 Answers
Reset to default 4setTimeOut
takes delay as parameter, so when setting timeout, capture currentServerTime + delay
say serverTriggerTime
and persist this in DB. Then, on restart of server, create the same timer using the serverTriggerTime
.
Then, delay = serverTriggerTime - currentServerTime
, use this delay to set new timer.
When setting timer
const date = Date.now();
const serverTriggerTime = date + delay; // time in milliseconds
On server restart:
serverTriggerTime = // retrieve from DB.
newDelay = serverTriggerTime - Date.now();
Also, set new timer only if newDelay >= 0, meaning the trigger time has not reached and will happen after newDelay time.
I would store the start times and durations in Redis and restart inplete timers when your application reloads. Some Redis modules:
https://github./joyent/node/wiki/modules#wiki-db-nosql-redis
本文标签: javascriptPersist setTimeout and setInterval across Nodejs restartsStack Overflow
版权声明:本文标题:javascript - Persist setTimeout and setInterval across Node.js restarts - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742259712a2442285.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论