views:

277

answers:

1

I'm creating a PowerShell script that I'm going to execute using Start-Job. The job should continuously run in the background until I tell it to stop using Stop-Job. It should execute a SQL command on a timer with a specified duration and output the results to the jobs pipeline so I can retrieve them using Receive-Job.

Right now the job runs properly but I don't have it setup to continue running after initial SQL command execution (I don't have the timer implemented).

What is the proper way to implement a timer in a PowerShell job so that the job runs continuously?

+1  A: 

While maybe not quite a timer as such, I have done similar things just using a loop:

while ($true) {
  "Hello"
  [System.Threading.Thread]::Sleep(1000)
}

You may want to further modify the script to sleep a computed amount of time:

while ($true) {
  $start = [DateTime]::Now
  "Hello"
  $end = [DateTime]::Now
  #computer difference from initial five minute marker (5*60*1000=300000)
  $wait = (5*60*1000) - ($end - $start).TotalSeconds
  if ($wait -gt 0) { [System.Threading.Thread]::Sleep($wait) }
}
Goyuix
is Thread.Sleep the best way to wait in PowerShell?
spoon16
I would use Start-Sleep 1 (for 1 second).
Keith Hill