Monday, July 23, 2007

Window Service timer problem - VB.NET

I wrote a Windows Service application in VB.NET before and i faced a problem. I used timer to do the schedule task in this application. I dropped a Timer Control on the designer then add the Tick event to do the schedule task. I can built, install, stop and restart the service. However the problem is it the Tick event never fires at all.

After that, i try to use code to create the timer. I changed to use System.Timers.Timer instead of System.Windows.Forms.Timer dropped on the designer from Toolbox. Then it is work already. The code is like below:-

Dim timerSchedule As System.Timers.Timer

Protected Overrides Sub OnStart(ByVal args() As String)
timerSchedule = New System.Timers.Timer(1000)
AddHandler timerSchedule.Elapsed, AddressOf timerSchedule_Elapsed timerSchedule.Start() End Sub

Private Sub timerSchedule_Elapsed(ByVal pSender As Object, ByVal pArgs As System.Timers.ElapsedEventArgs)
Try timerSchedule.Stop()
'call my a function to do the scheduled task
DoScheduledTask()
Catch ex As Exception
Finally
timerSchedule.Start()
End Try End Sub

Try to know more about System.Timers Namespace, it will here you more.

No comments: