Persist setTimeout and setInterval across Node.js restarts

setTimeOut 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 incomplete timers when your application reloads. Some Redis modules:

https://github.com/joyent/node/wiki/modules#wiki-db-nosql-redis