I know I haven’t been able to write for a long time now, and I’ll still be lagging up, but hopefully soon I’ll be back, with full speed, bringing you a new post every week.
Today I’ll show you how to use the System.Windows.Forms.Timer to control when to perform some action or call some procedures. A good example is when you maybe need to send a report to your boss, say every day at 4pm.
In this case, you need a timer object, that calls an event handler which checks the time against your system time to see if it is 4pm or after and then call the procedure that sends the report. Let’s see how you can go about, doing that.
What we need.
- A Timer object.
- A method to serve as an event handler
- Your custom method that does whatever work you want done when it’s time.
We’ll make use of the AddHandler statement to hook up the Timer’s Tick event with our event handler. The AddHandler statement is used to associate an event with an event handler at run time.
See the full code below.
Imports System
Module Sample
Public Class Test
Private Shared myTimer As New System.Windows.Forms.Timer()
Public Shared Sub Main
'hook up the event to the handler method
AddHandler myTimer.Tick, AddressOf CheckTime
' Sets the timer interval to 1 second and start it.
myTimer.Interval = 1000
myTimer.Start()
MsgBox("The timer is running now....")
Console.Read()
RemoveHandler myTimer.Tick, AddressOf CheckTime
End Sub
Public Shared Sub CheckTime(ByVal sender As System.Object, ByVal e As System.EventArgs)
If DateTime.Parse(DateTime.Now.ToShortTimeString) > DateTime.Parse("11:00 AM") Then
MsgBox("The time is : " & DateTime.Now.ToShortTimeString)
'Call SendPendingInvoices()
End If
End Sub
End Class
End Module
As you can see above, we created a new Timer object, and in our main procedure, or start up procedure, we hooked up the Timer.Tick event to our CheckTime event handler method, so that it gets called every time the tick event of the timer is fired. In our case that will be every 1 second.
To test the code, create a new blank console project and copy and paste the code above and simply click run. If your system time is greater than 11:00 AM then you should see a message box pop up every second showing you the current time from your system.
Hope this was helpful.
Till next time, yours truly.