I needed to multi-thread a task that had a thousand records to process and each one needed a 15 second sleep. Well as I found out, there is no built-in throttling to Start-Job, so I had 1000 powershell.exe try to launch. Not good to say the least. Anyway, after looking online I found throttling code and adapted it to something simple and sweet. All I need to do is inject a call to Throttle-Jobs before I do a Start-Job and it'll wait for the number of running jobs to drop below the maximum.
- function Throttle-Jobs {
- param( [int] $maximum = 25, [TimeSpan] $interval = [TimeSpan]::FromSeconds(1) )
- while ( (Get-Job -State Running | Measure-Object).Count -gt $maximum ) {
- Start-Sleep -Milliseconds $interval.TotalMilliseconds
- }
- }
This is fantastic :) I've been looking for something like this and all the other examples I've found online are massively over complex!
ReplyDeleteTHANKS!
Ditto to wicky's comment. This was easily to implement in an already fleshed-out framework for job management I had. The other blogs are great for starting from scratch but this elegant solution let's you just use the function as you said, just before running the start-job cmdlet. Well done! Thank you! :)
ReplyDelete