Using the Timer object and Event Handlers to automatically control actions.

23 Apr

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.timers

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.

  1. A Timer object.
  2. A method to serve as an event handler
  3. 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.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: