Xamarin Forms Timer

A timer will execute a piece of code on a timed interval. In Xamarin, each platform has its own native timer, and the Xamarin Forms timer translates to this. There is no System.Threading.Timer in the more common profile 259 or 111 based PCL’s, however if you use .NET Standard, you will have access to System.Threading.Timer. However, if you have Profile 151, or Profile 44, System.Threading.Timer is available, however these profiles are a little less common, but may be an option for you.

However for the focus of this post, we are looking at the Xamarin Forms Timer.

clock

Xamarin Forms Timer

To get started, here is the basic timer.

Device.StartTimer(TimeSpan.FromSeconds(30), () =>
{
    // Do something
   
    return true; // True = Repeat again, False = Stop the timer
});

At the platform level, it is using the following.

iOS

public void StartTimer(TimeSpan interval, Func<bool> callback)
{
    NSTimer timer = NSTimer.CreateRepeatingTimer(interval, t =>
    {
        if (!callback())
            t.Invalidate();
    });
    NSRunLoop.Main.AddTimer(timer, NSRunLoopMode.Common);
}

Android

public void StartTimer(TimeSpan interval, Func<bool> callback)
{
    var handler = new Handler(Looper.MainLooper);
    handler.PostDelayed(() =>
    {
        if (callback())
            StartTimer(interval, callback);

        handler.Dispose();
        handler = null;
    }, (long)interval.TotalMilliseconds);
}

UWP

public void StartTimer(TimeSpan interval, Func<bool> callback)
{
    var timer = new DispatcherTimer { Interval = interval };
    timer.Start();
    timer.Tick += (sender, args) =>
    {
        bool result = callback();
        if (!result)
            timer.Stop();
    };
}

Timer

While the timer is simple in its usage, there are a number of points you must consider when using one.

Life cycle

The life cycle of a Timer is something to keep note of. The timer is a global timing system, meaning any reference you put into the code, will be referenced until the timer is stopped. Hence you must put a condition inside the timer to stop it, when it is no longer needed. Failure to do this, may result in memory leaks.

Threading

Any code run in a timer will run on the main UI Thread. Make sure you don’t block the UI thread or do any intensive calculations. Ensure you move the code to a background thread if appropriate.

App State

If your app is backgrounded, the timer will continue to run, until it is at least terminated or killed.

Microsoft MVP | Xamarin MVP | Xamarin Certified Developer |
Exrin MVVM Framework | Xamarin Forms Developer | Melbourne, Australia

Related Posts

7 Comments

  1. Andrei Nitescu

    What about using a `while` loop with Task.Delay() ?
    No lambdas, no event handlers, is cross platform without Xamarin Forms, it looks cleaner because of async, and combined with TaskCancellationSource it’s cancellable.

      1. Anil Kumar

        I tried using FluentScheduler, Quartz for scheduling. None of them are compatible with Xamarin Forms. I’ll go with Andrei’s solution. Thank you.

  2. JFMG

    We use Observable.Interval for repeated events and Observable.Timer for a one time event. These extensions are added by ReactiveUI.

Leave A Comment?