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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
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.exeas the program path, and the path to your script as the argument. -
If you choose
Run whether user is logged on or notI get an error:The directory name is invalid (0x87010B). ChoosingRun only when user is logged on“solves” this issue.
This took me quite a bit to figure out …
Method 3
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0