Repeat python function at every system clock minute

I've seen that I can repeat a function with python every x seconds by using a event loop library in this post:

import sched, time
s = sched.scheduler(time.time, time.sleep)
def do_something(sc): 
    print("Doing stuff...")
    # do your stuff
    s.enter(60, 1, do_something, (sc,))

s.enter(60, 1, do_something, (s,))
s.run()

But I need something slightly different: I need that the function will be called at every system clock minute: at 11:44:00PM, 11:45:00PM and so on.

How can I achieve this result?


Solution 1:

Use schedule.

import schedule
import time

schedule.every().minute.at(':00').do(do_something, sc)
while True:
    schedule.run_pending()
    time.sleep(.1)

If do_something takes more than a minute, threadidize it before passing it to do.

import threading
def do_something_threaded(sc):
    threading.Thread(target=do_something, args=(sc,)).start()

Solution 2:

Exactly 0 is very hard to accomplish (since there is always a small delay) but You can check if the minute has changed:

import datetime
minute = None
while True:
    if datetime.datetime.now().minute != minute:
        print(f'Do something {datetime.datetime.now()}')
        minute = datetime.datetime.now().minute 

result at my mahcine:

Do something 2022-01-21 11:24:39.393919
Do something 2022-01-21 11:25:00.000208

So it checks if there is a new minute and calls again the datetime function. The delay is around 0.2 milliseconds.

Solution 3:

If you think along the lines of a forever running program, you have to ping the system time using something like now = datetime.now(). Now if you want 1 sec accuracy to catch that :00 window, that means you have to ping a lot more often.

Usually a better way is to schedule the script execution outside using Windows Task Scheduler or Crontab in Linux systems.

For example, this should run every XX:YY:00:

* * * * * python run_script.py