0

I have a code that I need to run every 2 hours, it doesn't have to be exactly every 2 hours, is there any reason I shouldn't use time.sleep(7200) for this?

I don't really know any other methods so I decided to take the lazy way out.

My code now reads something like this:

while True:
  command
  time.sleep(7200)

I know it would work but I'm wondering if it would take resources away from my system if I did that way.

MarinaF
  • 35
  • 1
  • 2
  • 13
  • 1
    Possible duplicate of [Scheduling Python Script to run every hour accurately](https://stackoverflow.com/questions/22715086/scheduling-python-script-to-run-every-hour-accurately) –  Jul 25 '19 at 15:22
  • 5
    The reason not to use it is that you're running python all the time for no reason. instead you should use a cron job (or equivalent for your OS) – Chris_Rands Jul 25 '19 at 15:22

2 Answers2

0

ignoring whether those points are relevant to you or not, some possible reasons not to use time.sleep() the way you presented are:

  • If your script crashes for any reason, which includes e.g. reboots, the schedule stops.
  • The timing is inaccurate. It depends on when you started the python script and shifts a bit for every execution, as the execution itself takes up some time too.
  • You will have a long-running, idling python process, which unnecessarily binds some resources.
  • If you want any feedback on a per-execution basis, you have to manually program that.
  • If you want to change the schedule, you have to change the code itself, instead of e.g. a crontab file.
  • Similarly, you also can't easily change the code around the time.sleep() call without restarting the script and therefore resetting the schedule.
  • someone/something needs to run your script. For example if you're running the script through ssh, you need to start it as a separate process so it doesn't die with your ssh session, which also makes stopping it again harder (have to send a process signal).
Felk
  • 7,720
  • 2
  • 35
  • 65
0

if you're handling cleanups and graceful exits within your code, there is no problem in using time.sleep().

This answer might help if you want to know more : Scheduling Python Script to run every hour accurately

jatayu
  • 11
  • 3