Schedule Python Script – Windows 7

Question:

I have a python script which I would like to run at regular intervals. I am running windows 7. What is the best way to accomplish this? Easiest way?

Asked By: Btibert3

||

Answers:

A simple way to do this is to have a continuously running script with a delay loop. For example:

def doit():
    print "doing useful things here"

if __name__ == "__main__":
    while True:
        doit()
        time.sleep(3600) # 3600 seconds = 1 hour

Then leave this script running, and it will do its job once per hour.

Note that this is just one approach to the problem; using an OS-provided service like the Task Scheduler is another way that avoids having to leave your script running all the time.

Answered By: Greg Hewgill

You can do it in the command line as follows:

schtasks /Create /SC HOURLY /TN PythonTask /TR "PATH_TO_PYTHON_EXE PATH_TO_PYTHON_SCRIPT"

That will create an hourly task called ‘PythonTask’. You can replace HOURLY with DAILY, WEEKLY etc.
PATH_TO_PYTHON_EXE will be something like: C:python25python.exe. Check out more examples by writing this in the command line:

schtasks /?

Otherwise you can open the Task Scheduler and do it through the GUI.
Hope this helps.

Answered By: Glen Robertson

You can use the GUI from the control panel (called “scheduled tasks”) to add a task, most of it should be self-explanatory, but there are two things to watch out for:

  • Make sure you fill in C:python27python.exe as the program path, and the path to your script as the argument.

  • If you choose Run whether user is logged on or not I get an error: The directory name is invalid (0x87010B). Choosing Run only when user is logged on “solves” this issue.

This took me quite a bit to figure out …

Answered By: Martin Tournoij
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.