Matt
Matt

Reputation: 55

Python Sleep Until a Certain Time

I have a Python script and I want too run it at 3 am. Would like to simply put something like this at the top of it.

while not 3am:
    sleep(10)

That way it keeps sleeping for 10 seconds until it's 3am. At 3am, it executes the rest of the code below this and then exits the script. Is there a simple way to do that?

Upvotes: 0

Views: 7992

Answers (1)

Raymond Hettinger
Raymond Hettinger

Reputation: 226346

Solution with a sleep-wait loop:

import datetime
import time

target_time = datetime.datetime(2017, 3, 7, 3)  # 3 am on 3 July 2017
while datetime.datetime.now() < target_time:
    time.sleep(10)
print('It is 3am, now running the rest of the code')

If instead of sleeping, you want to do other work, consider using threading.Timer or the sched module.

Upvotes: 7

Related Questions