Blog Archives
Creating a timer event in Powershell
Recently I needed a timer to monitor something so I did a quick google search which to my surprise didn’t come up with much. Perhaps because this isn’t too hard, but still, I thought I would post a little something on how to do this.
If you are the developer type person then you might want to take a look at this article on the different .NET timer classes. A good read and good to know but not really needed for this post.
The timer class I’ll be using is the System.Timers.Timer (Which can be shortened to Timers.Timer because powershell assumes the system. namespace )
| $timer = new-object timers.timer $action = {write-host "Timer Elapse Event: $(get-date -Format ‘HH:mm:ss’)"} $timer.Interval = 3000 #3 seconds Register-ObjectEvent -InputObject $timer -EventName elapsed ` –SourceIdentifier thetimer -Action $action $timer.start() #to stop run |
You’ll notice it will start to spit out the Timer Elapsed Event notices, which is all well and good, but doesn’t do much for us.
In my case I have a background process going that has an event that I’ve registered for, but, I’ve found a problem with it (a post to come on that) so I need a timer to monitor this object. Lets say my background job sets a variable, $complete, to 1 when its done. We can monitor that variable building off of the pervious code.
| $complete = 0 $action = { write-host "complete: $complete" if($complete -eq 1) { write-host "completed" $timer.stop() Unregister-Event thetimer } } Register-ObjectEvent -InputObject $timer -EventName elapsed ` –SourceIdentifier thetimer -Action $action $timer.start() #to stop |
Once we change the $complete variable to 1 and the timer goes off it checks that, finds that it should stop and cleans itself up.
Enjoy!
