Created
July 5, 2019 19:56
-
-
Save countzero/ca1fc4cbecc1676aa7e4d2433a8cdce1 to your computer and use it in GitHub Desktop.
Execute PowerShell jobs in parallel with a max concurrency using the while loop polling strategy.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$maxConcurrentJobs = 5 | |
$pollingFrequencyInMilliseconds = 50 | |
for ($index=1; $index -le 23; $index++) { | |
while ($true) { | |
Get-Job -State Completed | Receive-Job | Remove-Job | |
$concurrencyLimitIsReached = $($(Get-Job -State Running).Count -ge $maxConcurrentJobs) | |
if ($concurrencyLimitIsReached) { | |
Write-Host "Reached concurrency limit of ${maxConcurrentJobs}, " -NoNewline | |
Write-Host "trying again in ${pollingFrequencyInMilliseconds} ms..." | |
Start-Sleep -Milliseconds $pollingFrequencyInMilliseconds | |
continue | |
} | |
$scriptBlock = { | |
Param ( | |
[string] [Parameter(Mandatory=$true)] $id | |
) | |
$durationInMilliseconds = $(Get-Random -Minimum 500 -Maximum 1000) | |
Start-Sleep -Milliseconds $durationInMilliseconds | |
Write-Host "Job #${id} completed in ${durationInMilliseconds} ms." | |
} | |
Write-Host "Starting Job #${index}..." | |
Start-Job $scriptBlock -Name "Job #${index}" -ArgumentList $index | Out-Null | |
break | |
} | |
} | |
Get-Job | Receive-job -AutoRemoveJob -Wait |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This will output the job results directly after they are completed in the order in which they have finished: