~ 4 min read

Scheduling Python Scripts Locally: A Step-by-Step Guide

By: Adam Richardson
Share:

Introduction to Scheduling Python Scripts Locally

In many situations, developers need to run Python scripts automatically at specific times or intervals. This can be very useful for automating repetitive tasks, generating reports, or updating databases. In this article, we shall delve into the world of task schedulers and automation tools that make it possible to run Python scripts at specific times locally.

Properties and Parameters of Task Schedulers

To run Python scripts at certain times, we can use operating system’s task schedulers such as Task Scheduler (Windows) and Cron (Linux and macOS). These schedulers have various properties and parameters that help users configure the frequency, time, and conditions to run the script.

Task Scheduler (Windows)

Properties of Task Scheduler:

  1. Name: A descriptive name for a new scheduled task.
  2. Description: An optional description for understanding the purpose of the task.
  3. Trigger: Specifies the timing of the task, such as daily, weekly, or on system startup.

Parameters of Task Scheduler:

  1. Trigger Type: Choose the frequency (One-time, daily, weekly, etc.).
  2. Start Time: Set the start date and time for the task.
  3. Repetition Interval: Set a regular interval for the task, if required.

Cron (Linux & macOS)

Cron uses a “crontab” file containing a series of lines that define when and how often a script should run. The elements of each line are as follows:

  1. Minute: The minute (0-59) when the script should run.
  2. Hour: The hour (0-23) when the script should run.
  3. Day of Month: The day of the month (1-31) when the script should run.
  4. Month: The month (1-12) when the script should run.
  5. Day of Week: The day of the week (0-7) when the script should run, where both 0 and 7 represent Sunday.
  6. Command: The command to execute, preceded by the execution path to the Python script.

A Simplified Example

Scheduling a Python Script in Windows

Let’s say we have a simple Python script named example_script.py, and we want to run it daily at 6 AM.

example_script.py:

import datetime

current_time = datetime.datetime.now()
print(f"Current time: {current_time}")

To schedule our Python script, follow these steps:

  1. Search for “Task Scheduler” in the Start Menu and open it.
  2. Navigate to “Create Task”:
    • Choose a name for the task and an optional description.
    • Set the trigger to Daily and set the start date and time to 6 AM.
  3. In the “Actions” tab, create a new action with these settings:
    • Action: Start a program
    • Program/script: python.exe
    • Add arguments: example_script.py
    • Start in (the path of your Python script)
  4. Press “OK” to create the task.

The script will now run at 6 AM daily.

Scheduling a Python Script in Linux

To schedule the same example_script.py to run daily at 6 AM, use the following steps:

  1. Open a terminal and type crontab -e.
  2. Add this line at the end of the file:
0 6 * * * /usr/bin/python /path/to/your/script/example_script.py

The script will run at 6 AM daily.

A Complex Real-Life Example

Imagine we want to download data from an API, process it, and send an email report every Friday at 5 PM.

Here is a Python script named report_generator.py that does this:

import requests
import datetime
import smtplib

def fetch_data():
    url = "https://api.example.com/data"
    response = requests.get(url)
    data = response.json()
    return data

def process_data(data):
    # Perform data processing
    # Create a summary report
    report = f"Weekly report for {datetime.date.today()}:\n\n"
    for item in data:
        # Process and append data to report
        report += f"{item}\n"
    return report

def send_email(report):
    to_email = "recipient@example.com"
    subject = "Weekly report"
    message = f"Subject: {subject}\n\n" + report
    
    server = smtplib.SMTP("smtp.example.com", 587)
    server.starttls()
    server.login("you@example.com", "your-password")
    server.sendmail("you@example.com", to_email, message)
    server.quit()

data = fetch_data()
report = process_data(data)
send_email(report)

Scheduling the script in Task Scheduler (Windows)

Follow the same steps as in the simplified example, but this time schedule the task on a weekly basis with the start time set to Friday, 5 PM.

Scheduling the script in Cron (Linux)

To schedule the report_generator.py script to run every Friday at 5 PM, add this line to the crontab:

0 17 * * 5 /usr/bin/python /path/to/your/script/report_generator.py

Personal Tips

  1. Test your Python script independently before scheduling it to ensure that it works correctly and handles errors appropriately.
  2. Always set the full path to the Python interpreter and the script when scheduling tasks.
  3. Make sure that your system’s time and timezone settings are correct, as task schedulers rely on system time.
  4. Log the outputs and errors of your scheduled tasks into a file for later analysis and debugging.
  5. For critical tasks, consider adding health checks that notify you in case of any failures.
Share:
Subscribe to our newsletter

Stay up to date with our latest content - No spam!

Related Posts