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?

1

3 Answers 3

68

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.

Sign up to request clarification or add additional context in comments.

1 Comment

"/RU system" will let you have the script run even when the user is not logged in, useful for servers, etc.
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 ...

2 Comments

This doesn't work for me. How do you see what the error is?
@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.
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.

2 Comments

What's the advantage of this compared to Task Scheduler? Or other way around, why mess with TS, this seems cleaner and easier.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.