Schedule a Task using Python

The ‘schedule‘ library can be used to schedule a task in Python.

The command to install the ‘schedule‘ library is:

pip install schedule

(1) To schedule a task in Python to run every day (for example, at 10:00 am every day):

import schedule
import time


def daily_task():
    print("This task runs every day")


# Schedule the task to run every day at ten am
schedule.every().day.at("10:00").do(daily_task)

# Run the scheduler continuously
while True:
    schedule.run_pending()
    time.sleep(1)

In the example above, the ‘schedule‘ library is used to create a task (daily_task) that prints a message every day at 10:00 am (to schedule a task to run at 10 pm, use the format of “22:00“). You can modify the scheduling as needed by changing the intervals and tasks.

(2) To schedule a task to run every hour:

import schedule
import time


def hourly_task():
    print("This task runs every hour")


# Schedule the task to run every hour 
schedule.every().hour.do(hourly_task)

# Run the scheduler continuously
while True:
    schedule.run_pending()
    time.sleep(1)

(3) To schedule a task to run every x minutes (for example, every 30 minutes):

import schedule
import time


def minutes_task():
    print("This task runs every 30 minutes")


# Schedule the task to run every thirty minutes 
schedule.every(30).minutes.do(minutes_task)

# Run the scheduler continuously
while True:
    schedule.run_pending()
    time.sleep(1)

(4) To schedule a task to run every x seconds (for example, every 3 seconds):

import schedule
import time


def seconds_task():
    print("This task runs every 3 seconds")


# Schedule the task to run every three seconds
schedule.every(3).seconds.do(seconds_task)

# Run the scheduler continuously
while True:
    schedule.run_pending()
    time.sleep(1)

Few notes to consider:

  • The time.sleep(1) line is included to prevent the script from consuming excessive CPU resources
  • The above scripts will not stop by themselves. They are designed to run indefinitely
  • To stop the script manually, you would need to interrupt the execution

If you want to add a condition to stop the script after a certain number of iterations or after a specific time, you can modify the script accordingly.

For example, to include a counter that stops the script after 5 iterations:

import schedule
import time


def seconds_task():
    print("This task runs every 3 seconds")


# Schedule the task to run every three seconds
schedule.every(3).seconds.do(seconds_task)

# Variable to count iterations
iterations = 0
max_iterations = 5

# Run the scheduler for five iterations
while iterations <= max_iterations:
    schedule.run_pending()
    time.sleep(3)
    iterations += 1

Leave a Comment