Managing the running time of background jobs. Timing out if not completed after x seconds, Managing the running time of background jobs. Timing out if not completed after x seconds, powershell powershell

Managing the running time of background jobs. Timing out if not completed after x seconds,


You can use a hash table of timers:

 $jobtimer = @{} foreach ($job in $jobs){   start-job -name $job -ScriptBlock {scriptblock commands}   $jobtimer[$job] = [System.Diagnostics.Stopwatch]::startnew()   }

The running time of each job will be in $jobtimer[$job].elapsed


Just walk through the list of running jobs and stop any that have run past your timeout spec e.g.:

$timeout = [timespan]::FromMinutes(1)$now = Get-DateGet-Job | Where {$_.State -eq 'Running' -and                  (($now - $_.PSBeginTime) -gt $timeout)} | Stop-Job

BTW there are more properties to a job object than the default formatting shows e.g.:

3 >  $job | fl *State         : RunningHasMoreData   : TrueStatusMessage :Location      : localhostCommand       :  Start-sleep -sec 30JobStateInfo  : RunningFinished      : System.Threading.ManualResetEventInstanceId    : de370ea8-763b-4f3b-ba0e-d45f402c8bc4Id            : 3Name          : Job3ChildJobs     : {Job4}PSBeginTime   : 3/18/2012 11:07:20 AMPSEndTime     :PSJobType     : BackgroundJobOutput        : {}Error         : {}Progress      : {}Verbose       : {}Debug         : {}Warning       : {}


You can specify the timeout option of Wait-Job:

-Timeout

Determines the maximum wait time for each background job, in seconds. The default, -1, waits until the job completes, no matter how long it runs. The timing starts when you submit the Wait-Job command, not the Start-Job command.

If this time is exceeded, the wait ends and the command prompt returns, even if the job is still running. No error message is displayed.

Here's some example code:

This part just makes some test jobs:

Remove-Job -Name *$jobs = @()1..10 | % {    $jobs += Start-Job -ScriptBlock {        Start-Sleep -Seconds (Get-Random -Minimum 5 -Maximum 20)    }}

The variable $timedOutJobs contains jobs that timed out. You can then restart them or what have you.

$jobs | Wait-Job -Timeout 10 $timedOutJobs = Get-Job | ? {$_.State -eq 'Running'} | Stop-Job -PassThru