Run a Python Script on a Schedule Using the sched Module.

Stack Overflow solution

First accepted answer on Stack Overflow

In [1]:
import sched
import time
from datetime import datetime, timedelta

# Create a scheduler instance.
scheduler = sched.scheduler(timefunc=time.time)

def reschedule(interval: dict=None):
    """Define how often the action function will run.
    Pass a dict interval {'hours': 1} to make it run every hour.
    """
    interval = {'minutes': 1} if interval is None else interval
    # Get the current time and remove the seconds and microseconds.
    now = datetime.now().replace(second=0, microsecond=0)
    # Add the time interval to now
    target = now + timedelta(**interval)
    # Schedule the task
    scheduler.enterabs(target.timestamp(), priority=0, action=get_report)

def get_report(analytics=None):
    # replace the print call with the code execute the Google API call
    print(time.ctime())
    
    reschedule() # Reschedule so it runs again.

if __name__ == "__main__":
    reschedule() # start

    try:
        scheduler.run(blocking=True)
    except KeyboardInterrupt:
        print('Stopped.')
Tue Oct 29 22:35:00 2019
Tue Oct 29 22:36:00 2019
Stopped.