14.5. Scheduling scripts
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.
Views: 0
Where to Move
Move chapter:
- ☰ 1. Chapter 1: What Is Programming?
- ☰ 1.1. What is a computer program?
- ☰ 1.2. What is Python?
- ☰ 1.3. Where is Python used?
- ☰ 1.4. How programming helps solve problems
- ☰ 1.5. Your first Python program
-
- ☰ 2. Chapter 2: Setting Up Python
- ☰ 2.1. Installing Python (Windows / macOS / Linux)
- ☰ 2.2. Using Python in the terminal
- ☰ 2.3. Using an IDE (IDLE / VS Code)
- ☰ 2.4. Running Python scripts
- ☰ 2.5. Python interactive mode
-
- ☰ 3. Chapter 3: Variables and Data Types
- ☰ 3.1. What is a variable?
- ☰ 3.2. Creating variables
- ☰ 3.3. Numbers
- ☰ 3.4. Test
- ☰ 3.5. Boolean values
- ☰ 3.6. Type checking
-
- ☰ 4. Chapter 4: Basic Operations
- ☰ 4.1. Arithmetic operations
- ☰ 4.2. Working with numbers
- ☰ 4.3. String operations
- ☰ 4.4. Combining text and variables
- ☰ 4.5. Comments in Python
-
- ☰ 5. Chapter 5: User Input and Output
- ☰ 5.1. Getting input from the user
- ☰ 5.2. Converting input to numbers
- ☰ 5.3. Formatting output
- ☰ 5.4. Writing interactive programs
-
- ☰ 6. Chapter 6: Conditions
- ☰ 6.1. Comparison operators
- ☰ 6.2. Logical operators
- ☰ 6.3. if, elif, else
- ☰ 6.4. Nested conditions
- ☰ 6.5. Common beginner mistakes
-
- ☰ 7. Chapter 7: Loops
- ☰ 7.1. Why loops are useful
- ☰ 7.2. for loops
- ☰ 7.3. while loops
- ☰ 7.4. Loop counters
- ☰ 7.5. break and continue
- ☰ 7.6. Loop exercises
-
- ☰ 8. Chapter 8: Data Collections
- ☰ 8.1. Lists
- ☰ 8.2. Tuples
- ☰ 8.3. Dictionaries
- ☰ 8.4. Sets (basics)
- ☰ 8.5. Choosing the right data structure
-
- ☰ 9. Chapter 9: Functions
- ☰ 9.1. Why functions matter
- ☰ 9.2. Defining functions
- ☰ 9.3. Parameters and arguments
- ☰ 9.4. Return values
- ☰ 9.5. Scope (local vs global)
- ☰ 9.6. Reusing code
-
- ☰ 10. Chapter 10: Working with Files
- ☰ 10.1. What is a file?
- ☰ 10.2. Reading text files
- ☰ 10.3. Writing and appending files
- ☰ 10.4. File paths
- ☰ 10.5. Simple file-based programs
-
- ☰ 11. Chapter 11: Errors and Debugging
- ☰ 11.1. Types of errors
- ☰ 11.2. Reading error messages
- ☰ 11.3. Common beginner errors
- ☰ 11.4. try and except
- ☰ 11.5. Debugging strategies
-
- ☰ 12. Chapter 12: Using Python Libraries
- ☰ 12.1. What is a library?
- ☰ 12.2. Importing modules
- ☰ 12.3. Standard libraries
- ☰ 12.3.1. math
- ☰ 12.3.2. random
- ☰ 12.3.3. datetime
-
- ☰ 12.4. Installing external libraries with pip
-
- ☰ 13. Chapter 13: Object-Oriented Programming
- ☰ 13.1. What is object-oriented programming?
- ☰ 13.2. Classes and objects
- ☰ 13.3. The `__init__` method
- ☰ 13.4. Attributes and methods
- ☰ 13.5. Encapsulation
- ☰ 13.6. Inheritance (basics)
- ☰ 13.7. Simple OOP examples
-
- ☰ 14. Chapter 14: Automation with Python
- ☰ 14.1. What is automation?
- ☰ 14.2. Automating simple tasks
- ☰ 14.3. Working with files and folders
- ☰ 14.4. Automating text processing
- ☰ 14.5. Scheduling scripts
- ☰ 14.6. Practical automation examples
-
- ☰ 15. Chapter 15: Web Development with Python
- ☰ 15.1. How the web works (basic overview)
- ☰ 15.2. Introduction to Flask
- ☰ 15.3. Creating a simple web server
- ☰ 15.4. Routing and templates
- ☰ 15.5. Handling user input (forms)
- ☰ 15.6. Very basic APIs
-
- ☰ 16. Chapter 16: Data Science with Python
- ☰ 16.1. What is data science?
- ☰ 16.2. Working with data
- ☰ 16.3. Introduction to NumPy
- ☰ 16.4. Introduction to pandas
- ☰ 16.5. Data visualization with matplotlib
- ☰ 16.6. Simple data analysis examples
-
- ☰ 17. Chapter 17: Mini Projects
- ☰ 17.1. Number guessing game
- ☰ 17.2. Simple calculator
- ☰ 17.3. To-do list
- ☰ 17.4. Password generator
- ☰ 17.5. Quiz application
- ☰ 17.6. Small web or data project
-
- ☰ 18. Chapter 18: Next Steps
- ☰ 18.1. How to practice Python
- ☰ 18.2. Writing clean and readable code
- ☰ 18.3. Choosing a specialization
- ☰ 18.3.1. Web development
- ☰ 18.3.2. Data science
- ☰ 18.3.3. Automation
- ☰ 18.3.4. Software development
-
- ☰ 18.4. Learning resources and communities
-
- ☰ 19. Appendix
- ☰ 19.1. Python syntax cheat sheet
- ☰ 19.2. Common errors and solutions
- ☰ 19.3. Glossary of terms
-
Comments
Please login to add a comment.
Don't have an account? Register now!