Home > Software design >  PowerShell, loop a task at fixed times (without Start-Sleep / Start-Job / Start-Process)
PowerShell, loop a task at fixed times (without Start-Sleep / Start-Job / Start-Process)

Time:10-05

I can easily loop through a task every minute for 24 hours as follows:

for($i = 0; $i -lt 1440; $i  ){
    # do task here ...
    Start-Sleep 60
}

However, the task can take from 1 second to 20 seconds, meaning that the Start-Sleep will get staggered.

How can I tell the loop to execute at an exact set time, such as say, at exactly 8 seconds past every minute (regardless of how long the task takes)?

I would prefer not to spawn the task off to a Start-Job or Start-Process as the task relies on a number of things earlier in the script and it would be cumbersome to have to have those things all defined within the job. I don't want the complexity of scheduled tasks either, as hopefully this can be controllable from a simple loop?

CodePudding user response:

You have to measure the processing time and subtract this value from your sleep value, e.g.:

$sleep = 60
for($i = 0; $i -lt 1440; $i  ){
    $processingTime = measure-command {# do task here ...}
    $newSleep = $sleep - $processingTime.totalSeconds
    If ($newSleep -lt 0){
        $newSleep = 0
    }
    Start-Sleep $newSleep
}
  • Related