piguy
piguy

Reputation: 526

BAT run python and kill it after period of time

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?

Upvotes: 1

Views: 711

Answers (1)

jhelphenstine
jhelphenstine

Reputation: 423

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.

Upvotes: 1

Related Questions