What is a good way to call a function at datetime in Python?
There 3 ways that I know of:
"Are we there yet?!" (check at if date has passed at interval (
time.sleep(interval)))
This is obviously bad. It can only be precise if interval is low, which becomes inefficient.Sleep off the difference (
time.sleep(timedelta.seconds))
This is better, but I don't like the idea of putting a thread to sleep for an insanely long time, e.g. 6 months if such is the date.Hybrid between the two above; sleep off the difference if difference is bellow interval. If above, sleep for an interval to prevent long sleeps.
I think this is the best out of all three when you think about long sleeps, but interval seems bad anyway.
Are there any more ways you can think of? Is there anything in standard library that can help me call a function at datetime behind the scene?
EDIT:
I'm asking this because I've actually developed my own Cron implementation in Python. The only problem is that I can't decide how my code should wait for next occurrence. One of the differences between my implementation and original Cron is support for seconds. So, simply sleeping for minimum possible interval (1 second in my case) is too inefficient.
I realize now that this question could perhaps be changed to "how does Cron do this?" i.e. "how does Cron check if any date has passed? Does it run constantly or is a process run each minute?". I believe the latter is the case, which, again, is inefficient if interval is 1 second.
Another difference is that my code reads crontab once and calculates the exact date (datetime object) of next occurrence from the pattern. While Cron, I assume, simply checks each minute if any pattern from crontab matches current time.
I'll stick to the "hybrid" way if there's no other way to do this.