Monday, January 21, 2008

Window Service timer problem - VB.NET

I had written 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 help you more.

3 comments:

Anonymous said...

Thank u very much WEC

Anonymous said...

banged my head on my desk for an hour before your post solved it. thanks!

Anonymous said...

thx, you are great!!!!