0

I have a batch script which starts a program that runs in cmd.exe I have tried using task scheduler to create a task which stops this cmd shell and starts a fresh one every hour to no avail. Are there any other ways to stop and start the same cmd and batch script every hour?

I tried making another batch with the following:

Taskkill /IM cmd.exe

and scheduling that to run every hour but since this batch also runs in a cmd shell it simply kills itself and not the previously running cmd shell.

Any help acheiving the stopping and restarting of the same cmd shell every x intervals would be greatly appreciated.

regards

Shaolin

EDIT:

The reason I want to restart this program every x intervals is because this particular program tends to hang, it may hang after 10 minutes or 10 hours. As a precaution i'd like to have it restart every hour.

Shaolin
  • 1
  • 1
  • 2

3 Answers3

2

It's a little unclear what you're trying to achieve and why, but I think batch scripting is the wrong tool for the job (Especially in 2013).

Powershell will give you far more predictable results and allow you provide far better reliability, for example:

$application = "C:\Windows\System32\notepad.exe"
$sleepTime = 10
$i = 1

while ($i = 1){
    Write-Host "Starting Process"
    $process = Start-Process $application -PassThru

    Write-Host "Waiting " $sleepTime "seconds"
    Start-Sleep -Seconds $sleepTime

    if(!$process.HasExited){
        Write-Host "Killing Process"
        $process.Kill()
    }else{
        echo "Process had already ended"
    }

    Start-Sleep -Seconds 2
}

Although I'm pretty sure there must be a better answer than using an infinite loop.

Dan
  • 15,430
  • 1
  • 36
  • 67
  • +1 For the use of powershell – Daryl Gill Apr 13 '13 at 18:19
  • The answer by @Dan using powershell work like a charm... Just edit the variable $application="C:\Windows\System32\notepad.exe" to match the application you want to start and run. e.g $application="full_path_to_application_to_run" Note the variable $sleepTime allows it to run for 10 Seconds in this case. In my case i did set $sleepTime = 3600 to allow my app run and restart after every 1 hour i.e 3600 Seconds – user2956084 Aug 01 '23 at 19:34
0

This sounds more like a logic problem. In the batch script you can type exit to close the cmd window within the logic. Otherwise you can look at using stop-process and start-process within powershell. I'd say we need a bit more information 'why' you need a fresh cmd window every hour.

Steve Schofield
  • 429
  • 2
  • 4
  • This particular program tends to hang, it may hang after 10 minutes or 10 hours. As a precaution i'd like to have it restart every hour – Shaolin Apr 13 '13 at 12:08
0

You should be able to add a /IF "CPUTIME gt 00:30:00"

taskkill /IM cmd.exe /IF "CPUTIME gt 00:29:00"
David Houde
  • 3,200
  • 1
  • 16
  • 19