How do I add a timer in Xamarin?

19,795

Solution 1

You can use the System.Threading.Timer class, which is documented in the Xamarin docs: https://developer.xamarin.com/api/type/System.Threading.Timer/

Alternatively, for Xamarin.Forms, you have access to a cross-platform Timer via the Device class:

Device.StartTimer(TimeSpan.FromSeconds(1), () =>
{
    // called every 1 second
    // do stuff here

    return true; // return true to repeat counting, false to stop timer
});

Solution 2

If you just need Android you can use

System.Threading.Timer

In shared code with Xamarin Forms you can use

Device.StartTimer(...)

Or you can implement one yourselfe with advanced features like:

public sealed class Timer : CancellationTokenSource {
    private readonly Action _callback;
    private int _millisecondsDueTime;
    private readonly int _millisecondsPeriod;

    public Timer(Action callback, int millisecondsDueTime) {
        _callback = callback;
        _millisecondsDueTime = millisecondsDueTime;
        _millisecondsPeriod = -1;
        Start();
    }

    public Timer(Action callback, int millisecondsDueTime, int millisecondsPeriod) {
        _callback = callback;
        _millisecondsDueTime = millisecondsDueTime;
        _millisecondsPeriod = millisecondsPeriod;
        Start();
    }

    private void Start() {
        Task.Run(() => {
            if (_millisecondsDueTime <= 0) {
                _millisecondsDueTime = 1;
            }
            Task.Delay(_millisecondsDueTime, Token).Wait();
            while (!IsCancellationRequested) {

                //TODO handle Errors - Actually the Callback should handle the Error but if not we could do it for the callback here
                _callback();

                if(_millisecondsPeriod <= 0) break;

                if (_millisecondsPeriod > 0 && !IsCancellationRequested) {
                    Task.Delay(_millisecondsPeriod, Token).Wait();
                }
            }
        });
    }

    public void Stop() {
        Cancel();
    }

    protected override void Dispose(bool disposing) {
        if (disposing) {
            Cancel();
        }
        base.Dispose(disposing);
    }

}

Solution 3

Yes, you can use System.Timers.Timer.

In Android we can use java.util.Timer like this:

    private int i;

    final Timer timer=new Timer();
    TimerTask task=new TimerTask() {
        @Override
        public void run() {
            if (i < 60) {
                i++;
            } else {
                timer.cancel();
            }
            Log.e("time=",i+"");
        }
    };
    timer.schedule(task, 0,1000);

In Xamarin.Android we can also use java.util.Timer like this:

[Activity(Label = "Tim", MainLauncher = true)]
public class MainActivity : Activity
{
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);
        Timer timer = new Timer();
        timer.Schedule(new MyTask(timer),0,1000);
    }
}

class MyTask : TimerTask
{
    Timer mTimer;
    public MyTask(Timer timer) {
        this.mTimer = timer;
    }
    int i;
    public override void Run()
    {
        if (i < 60)
        {
            i++;
        }
        else {
            mTimer.Cancel();
        }

        Android.Util.Log.Error("time",i+"");
    }
}
Share:
19,795
who's.asking
Author by

who's.asking

Updated on June 07, 2022

Comments

  • who's.asking
    who's.asking about 2 years

    So I need to have a timer to count down from 60 seconds. I am new to Xamarin and have no idea what it accepts. It will be used in Android.

    Any suggestions on how to start?

    Can you use System.Timers.Timer?