You’ve written a Python script that generates a daily report, cleans up old files, syncs data or sends reminder emails. It works perfectly when you run it by hand. Now you want it to run every morning at 7:30, even when nobody is logged in.
On Windows Server, the built-in Task Scheduler is the simplest reliable way to do this. It’s also where many scripts mysteriously “succeed” without doing anything. This guide covers both the setup and the gotchas.
Before you schedule: make the script scheduler-friendly
Most Task Scheduler problems are really script problems. Check these first.
1. Use absolute paths
When Task Scheduler runs your script, the current working directory may not be your project folder. Code like open("config.json") can fail silently or look in C:\Windows\System32.
Make paths relative to the script itself:
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent
config_path = BASE_DIR / "config.json"
output_dir = BASE_DIR / "reports"
2. Log to a file
There’s no console window to watch. Add logging:
import logging
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent
logging.basicConfig(
filename=BASE_DIR / "logs" / "daily_report.log",
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
)
def main():
logging.info("Report job started")
# ... your work ...
logging.info("Report job finished")
if __name__ == "__main__":
try:
main()
except Exception:
logging.exception("Report job failed")
raise SystemExit(1) # non-zero exit code so Task Scheduler shows failure
Create the logs folder beforehand, or create it in code.
3. Return a proper exit code
Exit with 0 on success and a non-zero code on failure. Task Scheduler records the Last Run Result, which makes monitoring much easier.
4. Use the virtual environment’s Python
If your project uses a virtual environment, point the task directly to its interpreter:
C:\apps\daily-report\.venv\Scripts\python.exe
You don’t need to “activate” the environment. Calling its python.exe directly uses the right packages.
Option A: Create the task with the GUI
- Open Task Scheduler → Create Task (not “Create Basic Task”, which hides important options).
- General tab
- Name:
Daily Sales Report - Select Run whether user is logged on or not
- Choose an account: a dedicated service account is best practice
- Tick Run with highest privileges only if the script truly needs admin rights
- Name:
- Triggers tab → New → Daily at 07:30
- Actions tab → New → Start a program
- Program/script:
C:\apps\daily-report\.venv\Scripts\python.exe - Add arguments:
C:\apps\daily-report\run_report.py - Start in:
C:\apps\daily-report
- Program/script:
- Settings tab
- Allow task to be run on demand
- Stop the task if it runs longer than: 1 hour (or your safe limit)
- If the task is already running: Do not start a new instance
“Start in” is the field people forget. Without it, relative paths break.
Option B: Create the task with schtasks (scriptable)
For repeatable server setup, use the command line (Command Prompt syntax; ^ continues a line):
schtasks /create /tn "Daily Sales Report" ^
/tr "\"C:\apps\daily-report\.venv\Scripts\python.exe\" \"C:\apps\daily-report\run_report.py\"" ^
/sc daily /st 07:30 /ru "SYSTEM"
Useful variations:
# Every 15 minutes
schtasks /create /tn "Sync Orders" /tr "..." /sc minute /mo 15
# Every Monday at 9 AM
schtasks /create /tn "Weekly Cleanup" /tr "..." /sc weekly /d MON /st 09:00
# Run once now (for testing)
schtasks /run /tn "Daily Sales Report"
# Check status
schtasks /query /tn "Daily Sales Report" /v /fo LIST
# Delete
schtasks /delete /tn "Daily Sales Report" /f
Note that schtasks doesn’t set a “Start in” folder, which is another reason to use absolute paths in your script.
Option C: PowerShell for full control
PowerShell’s scheduled task cmdlets let you set the working directory too:
$action = New-ScheduledTaskAction `
-Execute "C:\apps\daily-report\.venv\Scripts\python.exe" `
-Argument "C:\apps\daily-report\run_report.py" `
-WorkingDirectory "C:\apps\daily-report"
$trigger = New-ScheduledTaskTrigger -Daily -At 7:30am
Register-ScheduledTask -TaskName "Daily Sales Report" `
-Action $action -Trigger $trigger -User "SYSTEM" -RunLevel Highest
Choosing the right account
| Account | Pros | Cons |
|---|---|---|
| Your own user | Easy to test | Breaks when your password changes or you leave |
| SYSTEM | No password; always available | Very powerful; can’t access network shares as a user |
| Dedicated service account | Least privilege, auditable | Needs password management |
For scripts that access network drives, use a domain service account and UNC paths (\\fileserver\reports) instead of mapped drive letters like Z:. Mapped drives usually don’t exist in scheduled task sessions.
Hide the console window
Use pythonw.exe instead of python.exe to run without a console window. Be aware that print() output goes nowhere, so rely on logging.
Troubleshooting: “It runs but does nothing”
| Symptom | Likely cause | Fix |
|---|---|---|
| Last Run Result 0x1 | Script raised an error | Check your log file; test the exact command manually |
| Last Run Result 0x2 | File not found | Check paths, quotes and spaces in paths |
| Works manually, fails scheduled | Working directory or environment differences | Set “Start in”; use absolute paths |
| Can’t access network share | Mapped drives not available | Use UNC paths and a suitable account |
| Missing packages error | Wrong Python interpreter | Point to the virtual environment’s python.exe |
| Task never starts | Trigger disabled, or account lacks “Log on as a batch job” right | Check trigger and account rights |
| Runs twice | Overlapping long runs | Set “Do not start a new instance” |
Testing tip: Copy the exact program and arguments from the task into a command prompt running as the same account. If it fails there, you’ll see the error.
Monitoring scheduled jobs
- Turn on task history in Task Scheduler (Action menu → Enable All Tasks History).
- Check Last Run Result regularly, or script a check with
Get-ScheduledTaskInfo. - Have the script send an email or chat alert on failure. (See “Send Emails from Python Using SMTP: A Complete Example.”)
When to use something else
Task Scheduler is perfect for a handful of server jobs. Consider alternatives when you need:
- dependencies between many jobs, retries and dashboards: workflow tools like Airflow or Prefect
- cross-platform scheduling: cron on Linux
- cloud-based schedules: serverless scheduled functions
For most small and mid-sized setups, though, a well-configured Task Scheduler job with good logging does the job reliably for years.
Leave a Comment