Link Search Menu Expand Document

Schedule tasks with schedule

The schedule library allows you to schedule tasks to run at specific intervals. In this example, we demonstrate how to run a task every 10 minutes.

import schedule
import time
from datetime import datetime

def task():
    print(f"{datetime.now()}: Your task")

schedule.every(10).minutes.do(task)

while True:
    schedule.run_pending()
    time.sleep(1)

It is important to note the use of sleep(1). Without this brief pause, the infinite while loop would continuously execute, wasting resources.

In some cases, you may want to use a separate thread. If the task takes longer than 10 minutes to execute, it would block the next scheduled execution. This would prevent the task from running every 10 minutes as intended.

To ensure your task runs exactly every 10 minutes, regardless of how long the task takes, you can use threading as shown below:

import schedule
import time
import threading
from datetime import datetime

def task():
    print(f"{datetime.now()}: Your task")

def task_threaded():
    task_thread = threading.Thread(target=task)
    task_thread.start()

schedule.every(10).minutes.do(task_threaded)

while True:
    schedule.run_pending()
    time.sleep(1)

✏️ Exercises:

  • Instead of running task at a regular interval, use schedule to run it every day at 23:59.