Scheduling using System.Timers.Timer class
Author: Manoj G
Rating:
Visits: 15015
Discuss in Newsgroups
This is a simple VB.NET code snippet showing how you can write scheduling code using the System.Timers.Timer class
Public Function StartSchedule() As String
Dim myTimer As New System.Timers.Timer()
AddHandler myTimer.Elapsed, AddressOf MyScheduledOperation
myTimer.Interval = New TimeSpan(1, 0, 0, 0, 0).TotalMilliseconds
myTimer.Enabled = True
End Function
Public Sub MyScheduledOperation(ByVal sender As Object, ByVal e As ElapsedEventArgs)
Select Case e.SignalTime.DayOfWeek
Case e.SignalTime.DayOfWeek.Monday
'Do Monday's work
Case e.SignalTime.DayOfWeek.Tuesday
'Do Tuesday's work
Case e.SignalTime.DayOfWeek.Wednesday
'Do Wednesdays's work
Case e.SignalTime.DayOfWeek.Thursday
'Do Thursday's work
Case e.SignalTime.DayOfWeek.Friday
'Do Friday's work
Case e.SignalTime.DayOfWeek.Saturday
'Do Saturday's work
Case e.SignalTime.DayOfWeek.Sunday
'Do Sunday's work
End Select
End Sub
Explanation
The first thing to note is that I have used System.Timers.Timer class. There are other timers available. They are System.Threading.Timer ( but works only on Win 2K) and System.Windows.Forms.Timer (Works only in Windows Forms applications).
After creating the object of the Timer class, I have added an event handler for the Elapsed event. The Elapsed event fires when the time specfied by the Interval value elapses. In the sample shown above, the interval is set to 1 Day. Note that I have used TimeSpan structure for setting the interval. TimeSpan is a convineant way of storing time quanta. The TimeSpan constructor used above takes five params: Days, Hours, Minutes,Seconds and MilliSeconds respectively. Then, I use the TotalMilliseconds property of the TimeSpan to get the millisecond representation of the TimeSpan (The Interval property expects time in terms of milliseconds). Then, enable the timer.
The Elapsed event handler (MyScheduledOperation method in the sample) should expect an argument of type ElapsedEventArgs. This argument has a property called SignalTime which gives you the time the Elapsed event occured. In the sample above, I am checking what day of the week the event was raised and doing the corresponding job.
Uses
This example can be best applied to Windows Service applications which probably have to do some critical operations periodically.