46

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?

Matthias
  • 4,481
  • 12
  • 45
  • 84
Btibert3
  • 38,798
  • 44
  • 129
  • 168

3 Answers3

67

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:\python25\python.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.

Glen Robertson
  • 1,177
  • 8
  • 10
  • 3
    "/RU system" will let you have the script run even when the user is not logged in, useful for servers, etc. – Paolo Jan 19 '16 at 16:03
52

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:\python27\python.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 ...

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
  • This doesn't work for me. How do you see what the error is? – endolith Sep 30 '15 at 18:41
  • 1
    @endolith It's been years since I posted this answer, and don't really have a Windows machine for testing :-) From memory, I think you can see it in the same screen where you set the tasks somewhere... If you can't find it, it's probably a good topic for another question ;-) (maybe best posted on [SuperUser](https://superuser.com). – Martin Tournoij Oct 01 '15 at 20:59
14

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.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • 3
    What's the advantage of this compared to Task Scheduler? Or other way around, why mess with TS, this seems cleaner and easier. – Danijel Mar 09 '16 at 17:24
  • 3
    With this approach, there is no guarantee that the task is done once every hour... This only make sure there is one hour between tasks.. could make a difference if your task takes more than few seconds. – nyan314sn Nov 14 '17 at 21:47