Lo-Fi Python

Nov 25, 2018

Automated Python With Windows Task Scheduler

So you want to run your Python scripts automatically, but how?

I had heard of several popular scheduling libraries in Python like celery, Invoke, and schedule. One of my requirements is to run the python file "in the background", not in command prompt or an open window.

Enter Windows Task Scheduler, the de facto scheduler on Windows 7 computers. I have  scheduled a few scripts and it is working like a charm. In this post, I will schedule an example script to clean up my desktop at the beginning of each day. I have a habit of accumulating many Excel files there throughout the workday. This example automatically moves them into a folder.

Other Windows scheduling alternatives worth mentioning include creating a Windows service, or using schtasks if you prefer the command line.

Here's how to schedule a Python script to run:

  1. Search for Windows Task Scheduler in the start menu. Then select "Task Scheduler Library" to see all of the tasks Windows is running automatically.
  2. In the right toolbar, select "Create Basic Task" and give it a name and description. Note: I selected "Configure for: Windows 7, Windows Server 2008 R2".
general
  1. Set the time and frequency that the program will run in the "Triggers" tab.
  2. Under the "Actions" tab, select "Start a Program" from the dropdown. Under "Program/Script", enter the path to your Python.exe file. I set mine to a Python executable located within my virtual environment, but yours might be found wherever you have Python installed.
C:\Users\your_username\Desktop\36env\Scripts\python.exe
  1. Under "Add arguments (optional)", add the path to your .py script, within quotes:
"C:\Users\your_username\Desktop\36env\clean_desktop_excels.py"
actions
  1. Select additional conditions and settings as desired, such as "Wake the computer to run this task" and "Run with highest privileges".

I am enjoying this simple, easy and convenient scheduling manager for Windows. I figured most of this out thanks to this blog. Below is my script to clean my desktop each morning by moving my Excel files into a folder, using Python's stock shutil and os libraries. Set it and forget it, ya know what i mean? :D

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from shutil import move
import getpass
import os

# Desktop Spreadsheet File Cleaner: get all Desktop files and folders
src = f"C:/Users/{getpass.getuser()}/Desktop"
dir_items = os.listdir(src)
excel_files = [item for item in dir_items if ".csv" in item or ".xls" in item]
dst = f"C:/Users/{getpass.getuser()}/Desktop/Excels"
os.makedirs(dst, exist_ok=True)
for xl in excel_files:
    path_to_file = src + xl
    move(path_to_file, dst)

Additional Reading

Troubleshooting Windows Task Scheduler - Windows Documentation