Table of Contents
Why Schedule Python Scripts?
Sometimes you want your Python program to run automatically:
- Every day at a certain time (e.g. send a report at 8:00 am)
- Every hour (e.g. clean up a folder)
- Once a week (e.g. back up some files)
- After your computer starts
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:
- On Windows using Task Scheduler
- On macOS / Linux using
cron - From inside Python using a scheduling library (for simple setups)
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:
- The full path to
python.exe - The full path to your script file
Typical Python path (example):
C:\Users\yourname\AppData\Local\Programs\Python\Python312\python.exe
You can check using PowerShell or Command Prompt:
where pythonScript path example:
C:\Users\yourname\Projects\backup_reports.py
2. Create a Basic Task
- Press Start, type Task Scheduler, open it.
- In the right panel, click Create Basic Task...
- Give it a name, like
"Daily Report Backup", and click Next.
3. Choose When It Runs
You’ll see options like:
- Daily
- Weekly
- When the computer starts
- When you log on
Choose one (e.g. Daily) and set the time, then Next.
4. Tell It What to Run
On the Action step, choose:
- "Start a program"
Then fill:
- Program/script: path to
python.exe
Example:
C:\Users\yourname\AppData\Local\Programs\Python\Python312\python.exe - Add arguments (optional): your script filename (and any arguments)
Example:
C:\Users\yourname\Projects\backup_reports.py - Start in (optional): folder where the script lives
Example:
C:\Users\yourname\Projects
This “Start in” field is important if your script uses relative paths.
Click Next, then Finish.
5. Testing and Troubleshooting
To test:
- In Task Scheduler, go to Task Scheduler Library.
- Find your task by name.
- Right‑click it → Run.
If nothing seems to happen:
- Check the History tab for errors.
- Make sure your script:
- Writes logs to a file, or
- Prints output somewhere you can see (for testing)
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.pyCommon parts:
- Minutes:
0–59 - Hours:
0–23(24‑hour format) - Day of month:
1–31 - Month:
1–12 - Day of week:
0–7(0 or 7 = Sunday)
A * means “every value”.
2. Finding Your Python Path
In the terminal:
which python3Example output:
/usr/bin/python3Use that full path in your crontab.
3. Example Schedules
Every day at 3:00 am
0 3 * * * /usr/bin/python3 /home/you/backup_reports.pyEvery 15 minutes
*/15 * * * * /usr/bin/python3 /home/you/check_folder.pyEvery Monday at 9:30 am
30 9 * * 1 /usr/bin/python3 /home/you/send_report.pyRedirecting 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>>appends normal output tobackup.log2>&1also sends error messages into the same log file
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:
- Use full paths for everything (Python, script, files)
- If your script uses a virtual environment, activate it in the command:
0 3 * * * /bin/bash -c 'source /home/you/venv/bin/activate && python /home/you/backup_reports.py'- If you use environment variables, set them in a small shell script and call that script from cron.
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 scheduleExample: 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:
- Simple automation that stays running (e.g. a small service)
- Learning the idea of scheduling without touching OS tools
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:
- Make the script work when you run
python script.pymanually. - Add simple logging.
- Configure the schedule (Task Scheduler or cron).
- Test by running the scheduled job manually once (Run / test cron time).
- Check logs and fix issues.
- Only then rely on the schedule for important tasks.
Small Practice Ideas
Try creating small scripts and scheduling them:
- A script that writes the current time to a file every hour.
- A script that cleans a “DownloadsTemp” folder once a day.
- A script that appends “I ran!” to a log file every morning.
Each of these is a chance to:
- Use paths correctly
- Add logging
- Get comfortable with Task Scheduler or cron
Scheduling is what turns one‑off scripts into hands‑free automation that works while you’re doing something else—or even asleep.