How to call a function every minute in Python?

Have you ever wonder how to call a function every x minutes or seconds? This is usually very common when building projects that pull data from the web using a Raspberry Pi.  In this simple post, I will show you how to setup a simple project that illustrate the process and the library you can use to help with this task.

Requirement

The preferred installation method is by using pip:

sudo pip install apscheduler

Now import the BackgroundScheduler class.  Copy this line of code to the top of your file.

from apscheduler.schedulers.background import BackgroundScheduler

Define a variable to hold the Refresh Interval value.  This is optional but makes code cleaner and easy to modify in the future.

REFRESH_INTERVAL = 60 #second

Next, we will create our scheduler instance variable and start it by calling scheduler.start()

scheduler = BackgroundScheduler()
scheduler.start()

Now, all we need to do is add a job to the scheduler that runs on an interval. This job will run our myFunction every 60 seconds

scheduler.add_job(myFunction, 'interval', seconds = REFRESH_INTERVAL)

Complete sample code

import time
from apscheduler.schedulers.background import BackgroundScheduler

REFRESH_INTERVAL = 60 #seconds

scheduler = BackgroundScheduler()
scheduler.start()

def main():
    # Call our function the first time
    myFunction()

    # then every 60 seconds after that.
    scheduler.add_job(myFunction, 'interval', seconds = REFRESH_INTERVAL)

    # main loop
    while True:
        time.sleep(1)

def myFunction():
    print "Calling this fucntion every %d seconds" % REFRESH_INTERVAL

if __name__ == "__main__":
    main()

The Results

If you have any issues or questions, please leave a comment below and I will do my best to help you.