Kahibaro
Discord Login Register

Scheduling scripts

Why Schedule Python Scripts?

Sometimes you want your Python program to run automatically:

Instead of sitting at your computer and running the script by hand, you can let the system do it for you.

In this chapter, you’ll see practical ways to schedule Python scripts:

You do not need to become an expert in any of these tools. The goal is to understand the basic idea and have some copy‑paste‑and‑adjust examples you can adapt.

General Idea: Script First, Schedule Second

Before scheduling, you should have a Python file that runs correctly on its own.

Example: backup_reports.py

import shutil
from datetime import datetime
from pathlib import Path
SOURCE = Path("C:/Users/you/Documents/reports")
DEST = Path("D:/Backups/reports")
def backup():
    timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    dest_folder = DEST / f"backup_{timestamp}"
    shutil.copytree(SOURCE, dest_folder)
    print("Backup complete:", dest_folder)
if __name__ == "__main__":
    backup()

You should be able to run:

python backup_reports.py

and see that it works.
Only after that do you set up a schedule.

Scheduling on Windows: Task Scheduler

Windows has a built‑in tool called Task Scheduler that can run programs at specific times.

1. Find Your Python and Script Paths

You need:

Typical Python path (example):

You can check using PowerShell or Command Prompt:

where python

Script path example:

2. Create a Basic Task

  1. Press Start, type Task Scheduler, open it.
  2. In the right panel, click Create Basic Task...
  3. Give it a name, like "Daily Report Backup", and click Next.

3. Choose When It Runs

You’ll see options like:

Choose one (e.g. Daily) and set the time, then Next.

4. Tell It What to Run

On the Action step, choose:

Then fill:

This “Start in” field is important if your script uses relative paths.

Click Next, then Finish.

5. Testing and Troubleshooting

To test:

  1. In Task Scheduler, go to Task Scheduler Library.
  2. Find your task by name.
  3. Right‑click it → Run.

If nothing seems to happen:

Example of adding simple logging to a file:

from datetime import datetime
with open("backup_log.txt", "a", encoding="utf-8") as f:
    f.write(f"Backup started at {datetime.now()}\n")

Now you can open backup_log.txt to see if the script actually ran.

Scheduling on macOS / Linux: cron

On macOS and most Linux systems, there is a built‑in scheduler called cron.

You create a list of jobs (called a crontab) telling cron when and what to run.

1. Crontab Basics

Open a terminal and type:

crontab -e

The first time, it may ask you which editor to use. If you’re not sure, choose something simple like nano.

Each line in the crontab has this general format:

$$
\text{minute } \ \text{hour } \ \text{day-of-month } \ \text{month } \ \text{day-of-week } \ \text{command}
$$

Example: run at 3:00 am every day:

0 3 * * * /usr/bin/python3 /home/you/backup_reports.py

Common parts:

A * means “every value”.

2. Finding Your Python Path

In the terminal:

which python3

Example output:

/usr/bin/python3

Use that full path in your crontab.

3. Example Schedules

Every day at 3:00 am

0 3 * * * /usr/bin/python3 /home/you/backup_reports.py

Every 15 minutes

*/15 * * * * /usr/bin/python3 /home/you/check_folder.py

Every Monday at 9:30 am

30 9 * * 1 /usr/bin/python3 /home/you/send_report.py

Redirecting Output to a Log File

Cron doesn’t show you the script’s output on screen, so you usually redirect it to a log file.

Example:

0 3 * * * /usr/bin/python3 /home/you/backup_reports.py >> /home/you/backup.log 2>&1

Now you can open backup.log to see what happened.

4. Environment Gotchas

Cron runs with a minimal environment, which can cause issues.

Common tips:

0 3 * * * /bin/bash -c 'source /home/you/venv/bin/activate && python /home/you/backup_reports.py'

Scheduling Inside Python (While the Program Runs)

Sometimes you don’t need system‑level scheduling. You just want your program to do something every X seconds/minutes while it’s running.

You can do this in pure Python with time.sleep() or a library like schedule.

Simple Loop with `time.sleep`

Example: check a folder every 10 minutes in a running script:

import time
def check_folder():
    print("Checking folder...")
while True:
    check_folder()
    # wait 10 minutes = 600 seconds
    time.sleep(600)

This only runs while the script itself is running; it does not replace system scheduling.

Using the `schedule` Library

Install:

pip install schedule

Example: run a function every day at 08:00 while the script is running:

import schedule
import time
def job():
    print("Running daily job")
schedule.every().day.at("08:00").do(job)
while True:
    schedule.run_pending()
    time.sleep(1)

This is handy for:

But if you want it to run even when the script is not already running, you still need system tools like Task Scheduler or cron.

Practical Tips for Reliable Scheduling

1. Use Absolute Paths

Inside scheduled scripts, avoid:

open("data.txt")

Instead, use full or constructed paths:

from pathlib import Path
BASE_DIR = Path(__file__).parent
DATA_FILE = BASE_DIR / "data.txt"
with open(DATA_FILE, "r", encoding="utf-8") as f:
    content = f.read()

This makes your script less dependent on the “current folder”.

2. Log What Happens

Because you often don’t see your script running, logging is very helpful.

Example minimal logger:

from datetime import datetime
from pathlib import Path
def log(message):
    log_file = Path(__file__).with_name("script.log")
    with log_file.open("a", encoding="utf-8") as f:
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        f.write(f"[{timestamp}] {message}\n")
log("Script started")

Then you can open script.log to see when it ran and what it did.

3. Start Simple, Then Add Complexity

A good approach:

  1. Make the script work when you run python script.py manually.
  2. Add simple logging.
  3. Configure the schedule (Task Scheduler or cron).
  4. Test by running the scheduled job manually once (Run / test cron time).
  5. Check logs and fix issues.
  6. Only then rely on the schedule for important tasks.

Small Practice Ideas

Try creating small scripts and scheduling them:

Each of these is a chance to:

Scheduling is what turns one‑off scripts into hands‑free automation that works while you’re doing something else—or even asleep.

Views: 17

Comments

Please login to add a comment.

Don't have an account? Register now!