Monday, April 19, 2010

Timers in Windows Services

Occasionally I have to create a windows service. In most windows services I need to create a timer to execute a certain method periodically. Since I don't work with windows services often enough I always get stumped at the best method to create the timer. I know that by dragging the Timer object from the Toolbox adds the timer from the Windows Forms namespace. That timer has a Tick even which I haven't been able to make work in a Windows Service project. So if you create a windows service in Visual Studio 2008 and you need a timer this is the code you need to add to your class for the service:

Private WithEvents Timer1 As New System.Timers.Timer()

Private Sub Timer1_Elapsed(ByVal sender As System.Object, ByVal e As System.Timers.ElapsedEventArgs) Handles Timer1.Elapsed
    'Some code
End Sub

Afterwards you can set the elapse time of the timer and enable it in your service start event:

Protected Overrides Sub OnStart(ByVal args() As String)

    Timer1.Interval = 60000 '60000 = 1 minute

    Timer1.Enabled = True

End Sub

Happy coding!

No comments:

Post a Comment