I run a Python script 4 times a day at what I'd like to be an exact, down to the second, time. I have been doing this for a while using launchd on my Mac and the script has been running at nearly the exact second I want. For example, I've set launchd to start running the script at exactly 6 am and the script generally starts running at 6 am plus 100 or 200 milliseconds; exactly what I want. However, for some unknown reason (perhaps a just-before-this-started-happening OS X update?), the script is now starting to run anywhere from a few seconds to more than a few seconds after 6 am, too late for the ultimate purpose of the script. I'm now thinking that a more robust way to make sure the main part of my script runs at exactly the second I want is to start the script sometime before 6 am, perhaps at 5:59 am, and then in the script itself, have it check the time every second (or more) and then when the exact second I want the rest of the script to run comes, the rest of the script will run. So, my question is, how do I run a loop, or whatever, in the script itself, which will then kick off the rest of the script at the exact (or nearly exact) moment, for example 6:00:00 am?
Okay, the question was marked as a duplicate but it still took a bit to figure out the best way to resolve my problem. Just in case anyone is looking for the answer here, here is what I did:
import datetime
import time
##### build in a timer to make sure the script starts to execute at the exact time and second, i.e. 6am, 10am, 2pm, and 6pm, PDT
secs = datetime.datetime.now().strftime("%S.%f")
secs = float(secs)
sleep_secs = 60 - secs
time.sleep(sleep_secs)