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 =, 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
    reschedule() # Reschedule so it runs again.

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

    except KeyboardInterrupt:
Tue Oct 29 22:35:00 2019
Tue Oct 29 22:36:00 2019