简体   繁体   中英

Node.js setTimeout for 24 hours - any caveats?

Simple question, I want to set 24 or 12 hours timeout in Node.js to periodically (once or twice a day) check some db data and clean suspicious garbage, if any.

Is there any possible problems or performance issues, caused by setting huge timeout, that i need to be aware of? I don't mind if it's not exact 12-24hr in ms, and don't mind loosing this timeout on server crash, as I will run same garbage collector on server startup anyway.

  • I'm not using native OS cron to run separate script as I need to access current Node.js process data inside this script.
  • In the end I decided to use https://www.npmjs.com/package/cron package for its ability to shedule at specific time (presumably on time of low server load).
  • Thanks everyone for quick responses!

I've had success using the package cron . It's simple to use and is generally compatible with a CronTab. I've had a job that runs once a month and this has worked consistently since last year, so I can attest to it.

That being said, this package ultimately does just use setTimeout internally so there's no real issue with you doing that. If your timeout number is too large (larger than the maximum JavaScript integer) there may be a problem, but 1000 * 60 * 60 * 24 is significantly smaller than that.

Obviously if your system goes down or the script crashes for some other reason the timeout won't work.

You could also just use crontab directly if it's available (or Windows task scheduling).

Personally, I would use a cron job to do this sort of thing (in Unix/Linux), or a "scheduled task" in Windows. In any case, the work would be done entirely on the server, by the server ... and thus, there's really no reason to have a JavaScript app (on "some other" computer) to be involved with it.

More generally: "no, don't tell someone to 'go to sleep for 12 hours,' somehow trusting that this means s/he will wake up in time." Instead, use an alarm-clock. Calculate the absolute-time at which the activity should [next] occur, then see to it that the activity does occur "not-sooner." Arrange for the computer that actually needs to do the work, to do the work at the appropriate time, using whatever scheduling facilities are available on that computer.

There should not be any problem at all, but in my opinion it is just better to do this thing with a OS cron job. This will use the OS timer, will call your node app; that will be clear to everybody, even to the one who has never seen node or JavaScript in action. Also it will automatically protect you from long-term memory leaks because your app will be killed after each iteration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM