How can I schedule task in future?
-
@julian I have just implemented my solution with setTimeout(). I think that is a good solution:
- I create timeout=setTimeout() and I put it in arrayTimers in my library.js
- I save in my database that I have a "timeout"
- I use "{ "hook": "static:app.load", "method": "loadTimer" }" to load timer in my arrayTimers when the server crash or it restarts.
- When the timeout is schedulated, I delete all value in db and I clearTimeout(myTimer).
Julian can explain me if my solution can be good or not for you? and can you explain the problem to use setTimeout()?
-
Hi @Doppy -- there's nothing inherently wrong with using
setTimeout
in the manner you've described, however it is not done simply because there is a better way to do it.For example, you're setting the timer, and saving a reference in the db so if the app restarts, it is re-loaded. That is fine, you'd do something similar with
node-cron
.However, when you call
setTimeout
, the function reference is held in memory and cannot be garbage collected if needed since at some arbitrary point in the future it will be called upon. I don't believe the same happens with cron but I may be mistaken. -
@julian the function reference has to be kept in memory for cron too, otherwise cron wouldn't know what to do.