Running code periodically with a Timer

A timer is a class that runs code periodically on some sort of interval (or period). They provide a great way to your application to be doing some processing while it might otherwise be idle, which can sometimes be a simple way to give the illusion of concurrency.

Timers are often used in conjunction with threads to provide UI updates for background processing.

Types of timers

Desktop and iOS projects can use the Timer class to create timers.

Web projects can use the WebTimer or Timer class to create timers. In most case you will want to use the WebTimer class which creates a timer that runs in the browser. Timers created using Timerr run on the server.

Timers on the Desktop have an Action event handler (on iOS and Web it's called Run) where you can put the code you want to run along with Period and Mode properties that let you specify how often the Action/Run event handler is called. In all cases, code run from a timer runs in the main (UI) thread so it is best to not have long-running code called by a timer as it will block the rest of your app from being able to do anything. This also means that if your app is busy doing processing it will be unable to call the Timer when its period is reached. If you need more precise control of your processing you will want to use Threading.

Avoid having long-running code called by a timer as it will block the rest of your app.

Using a Timer in a desktop project

For desktop projects, you use the Timer class to create a timer.

The code that you want to run periodically goes in the Action event. You specify the period in milliseconds using the Period property. It tells the timer how frequently the Action event is called. The Mode property is used in conjunction with this to specify if the timer is set to run multiple times, just a single time or is off completely.

You can drag a Timer from the Library onto your layout to create a Timer subclass that you can use. When you do this you get the classic Timer class. You put the code you want to run when the timer period is reached in its Action event handler. For a Timer that is set to run multiple times (Mode = ModeMultiple) and with a Period of 500 (1/2 second).

The following code in a timer will increase a counter displayed in a Label about every 1/2 second:

Var value As Integer
value = CounterLabel.Text.ToInteger
value = value + 1
CounterLabel.Text = value.ToString

You can set a Tolerance to tell the OS how precise you need the timer to be. A less precise timer makes better use of system resources and will not impact the battery on portable devices as much. Timer also has CallLater methods that are handy for when you need a one-time timer (for example to update the UI after a short period of time) and don't want to create a subclass.

For example, suppose you want to display some help text for a few seconds and then hide it. You can do this by creating a method to clear a Label (ClearLabel):

Sub ClearLabel
  MyLabel.Text = ""
End Sub

In another method, you set the Label help text and then use CallLater to tell the Timer to call the Clear method after 2 seconds: MyLabel.Text = "Help text goes here"

Timer.CallLater(2000, AddressOf ClearLabel)

Using a Timer in a web project

Web projects can use the WebTimer class to create a timer that runs in the web browser. This is useful for creating a session-specific timer that updates the UI. The simplest way to do this is to drag a Timer from the Library onto your layout, set the Period and Mode properties and add the Action event.

The same code from above also works with a web project increase a counter displayed in a Label every 1/2 second:

Var value As Integer
value = CounterLabel.Text.ToInteger
value = value + 1
CounterLabel.Text = value.ToString

You can also use Timer in a web app but these will run on the server and will not be session-specific so they are far less useful.

Using a Timer in an iOS project

iOS projects also use the Timer class to create a timer. You can drag the Timer from the Library onto your layout to add a timer. Set its Mode and Period properties and add the Action event for your code.

With a Period of 500 (milliseconds) and a Mode of Multiple, this code will increment a counter in a Label:

Var value As Integer
value = Integer.FromString(CounterLabel.Text)
value = value + 1
CounterLabel.Text = value.ToString

Using AddHandler with a Timer

You can also use a Timer without adding it to the layout, at least in desktop and iOS projects. In this case you would create a Timer instance in a property, create a method to serve as its Action event and then use the AddHandler command to tell the timer that the method will be called in place of the Action event.

Below is how you would do it for an iOS project.

Start by adding a property to the layout:

MyTimer As Timer

Next, add a ProgressBar to the layout (this example code uses MobileProgressBar). The Timer will simply update the ProgressBar. In the Opening event handler of the layout, instantiate the Timer and indicate that its Action event handler should be handled by a method, TimerAction, that you will add to the layout:

MyTimer = New Timer
MyTimer.Period = 1000
MyTimer.Mode = Timer.Modes.Multiple
AddHandler MyTimer.Action, AddressOf TimerAction

Now add the TimerAction method to the layout:

Sub TimerAction(sender As Timer)
  // This code works on iOS and uses MobileProgressBar.
  // Change the properties as appropriate for desktop apps.
  If ProgressBar1.Value < ProgressBar1.MaximumValue Then
    ProgressBar1.Value = ProgressBar1.Value + 1
  Else
    // Stop Timer and Remove the handler
    sender.Mode = Timer.Mode.Off
    RemoveHandler MyTimer.Action, AddressOf TimerAction
  End If
End Sub

It is important that the first parameter to TimerAction must be of the type of the original object, in this case Timer. When you run the project, the ProgressBar is updated once per second.

Using Timer in a console project

To use Timer in a Console project you have to either subclass the timer or use AddHandler to map the Action event to a method as shown above. In addition you have to add an event loop to your Console project using DoEvents.

As an example, the following code uses a Timer with AddHandler to display output to the terminal about once a second.

Create a new Console project and add a property to the App object:

MyTimer As Timer

Add the Run event to the App object and put this code to initialize the timer and map its Action event to the TimerAction method:

MyTimer = New Timer
MyTimer.Period = 1000
MyTimer.Mode = Timer.Modes.Multiple
AddHandler MyTimer.Action, AddressOf TimerAction

While True
  App.DoEvents
Wend

Now add the TimerAction method:

Public Sub TimerAction(sender As Timer)
  Print("Timer called.")
End Sub

Run the project and you'll see "Timer called." output to the Terminal (or Command shell) about once a second. Press Control-C to quit the console app.

See also

Timer, WebTimer classes