1

Using the script below within a BAT file

pushd C:\Users\Me
python -m bot_py synology

I execute a python script which never has an exit point (runs forever).

How can I tell within my BAT file that after a period of time, for example 5 hours, the python script should be killed/exited?

martineau
  • 119,623
  • 25
  • 170
  • 301
piguy
  • 516
  • 3
  • 10
  • 30
  • 2
    Task Scheduler is meant for this sort of thing... but if you must use a batch file, you can get the process ID via something like `tasklist | findstr`... then kill that process `taskkill /F /PID 18424`. This has some hints on getting the PID from a tasklist search: https://stackoverflow.com/questions/50555929/get-only-pid-from-tasklist-using-cmd-title – JacobIRR Jun 19 '19 at 22:54

1 Answers1

1

I created a batch file to demonstrate some components for your solution: Note: Credit to this answer for the PID extraction, pointed out by @JacobIRR.

TITLE Synology-Script

@echo off
for /F "tokens=2" %%K in ('
    tasklist /FI "WINDOWTITLE eq Synology-Script" /FI "Status eq Running" /FO LIST ^| findstr /B "PID:"    
') do (
    set pid=%%K
   echo %%K
)
echo "I'm scheduled to stop execution in 10 seconds"

timeout /t 10 /nobreak>nul
taskkill /PID %pid% /F

I used the TITLE paremeter to give me something to search for, and searched for that in the tasklist filter command on offer from this question. I recommend not including spaces in your title. I used this pid as an argument to taskkill, which terminates this process.

timeout /t 10 /nobreak>nul

This lets us sleep for 5 seconds, and stuffs the 'press ctrl+c' to nul, to keep it out of sight. You could set the 5 to whatever your desired sleep interval is.

jhelphenstine
  • 435
  • 2
  • 10