Question

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?

Was it helpful?

Solution

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) }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top