theharlotfelon
theharlotfelon

Reputation: 43

Schtaks - Command Prompt Parameters

I have a batch file I need to run ever x minutes. I know how to set up the scheduled task but I'm not sure if there is a parameter I can use to take advantage of the advanced setting "Stop the existing instance".

Basically, I want to be able to run the batch file every x minutes and when it runs again, if for some odd reason the first instance did not complete, I need it to be killed and the new instance to run.

Right now, I'm using:

schtasks /create /tn [TASKNAME] /tr C:\[DIR]\au.bat /sc MINUTE /mo 15 /ru "System"

which is great, but it lacks this extra part.

I already know the GUI is an option but the reason I am using the command prompt is that this is included in an installer clients will be using to make things easy for them and I don't want them to have to take this last step of going into the GUI to make this one change.

EDIT: Ended up going with something like this:

REM Checks to see if any instances of 'MYTITLE'
FOR /F "tokens=* USEBACKQ" %%F IN (`tasklist /v /fo csv ^| findstr /i MYTITLE`) DO (
    FOR /F "tokens=2 delims=," %%B IN (%%F) DO (
        taskkill /pid %%B /f
    )
)

title=MYTITLE

[BATCH FILE DOES STUFF HERE]

At launch, it looks to see if there are any instances that match MYTITLE and then kills those tasks. Then names itself and runs the batch. If it stays open, it will be killed next time the task it run.

Upvotes: 1

Views: 398

Answers (2)

theharlotfelon
theharlotfelon

Reputation: 43

Actually, the quick and easy answer to my question is to simply set up the task in Task Scheduler in the GUI and when all parameters are set, just export the xml file. Once this is done, you just have to create using the /xml option.

schtasks /create /tn [TASKNAME] /XML C:\[DIR]\schedule.xml

Upvotes: 2

Azeem
Azeem

Reputation: 14607

You can store the STATUS (i.e. {START, STOP, RUNNING, ...}) of your application along with its PID in environment variables.

For example (environment variables):

MY_APP_STATUS = 1
MY_APP_PID = 1234

For getting PID, see:
getting process ID of exe running in Bat File, how to get own process pid from the command prompt in windows

In your batch script, you can kill the running batch if the environment variable is set using the PID.

You can use taskkill command to do this:

taskkill /pid 1234 /f

You need to reset the STATUS flag after killing the existing running batch and update the PID with the new running instance.

Upvotes: 0

Related Questions