1

There's a lot of ambiguity about Windows' Task Scheduler ability to receive return codes from scripts. I've found several useful Stack Exchange answers but none of them quite fit my need.

I'm developing for Windows 7.

In the Scheduler I've set-up a task to run upon log-in. All it does is invoke a Python script myscript.py inside a virtual environment. So the action looks like this:

Program: PATH\\TO\\pythonw.exe (pythonw to run in hidden Window)

Arguments: Path\\TO\\myscript.py

Now this myscript.py is a "run-forever script":

bot = Bot(os.getenv("TOKEN", None))
bot.run()

run() is basically a polling mechanism that never exists as long as no exceptions occur. That's why when my Task is triggered in Scheduler, it always shows as "running" (is this a good practice?)

Which brings me to the question: How can I tell Task Scheduler to restart this task if it exists? basically, make sure one (and only one) instance of this script is running at all times, no matter what.

zerohedge
  • 135

1 Answers1

0

If you don't end up getting an answer about doing this purely with Windows Task Scheduler, one easy way to do it is using AutoHotkey.

Your .ahk file would go something like the below, and you'd start the ahk script with your scheduled task. Note that pythonw.exe may need to be python.exe, or py.exe perhaps - check task manager to see what it is while your script is running (I think maybe pythonw.exe though based on your description). Note that this assumes you won't have any other scripts running using pythonw / python. If you run this script, it will kill any other instances of itself and of pythonw.exe and then it will start your script. It will also run in a loop to watch for your script to close and then it will start it again.

#SingleInstance force
IfWinExist, ahk_exe pythonw.exe
WinKill, ahk_exe pythonw.exe
Launch:
;may want to call SetWorkingDir here or else pass as an argument to the below command
Run, PATH\\TO\\pythonw.exe Path\\TO\\myscript.py
Sleep, 5000
WinWaitClose, ahk_exe pythonw.exe
Sleep, 5000
Goto, Launch
g491
  • 604