Simple Timer for Xamarin Forms using Device Timer

While developing your application in Xamarin that requires a Timer, you have the option to use the Device Timer. However, one of the first caveat your would notice is that while Device Class has a Device.StartTimer method, it does not exposes a Stop method, leaving it to your own class to handle it.

I started by writing an interface for my proposed Timer Class ( in my case a Countdown timer), so that I could use it for mocking for the sake of my Unit Tests. This is how my interface looked like.

public class TimerEventArgs:EventArgs
{
public TimeSpan TimeRemaining { get; set; }
}

public interface ICountdownTimer
{
void Start(TimeSpan CountdownTime);
void Stop();

event EventHandler<TimerEventArgs> Ticked;
event EventHandler Completed;
event EventHandler Aborted;
}
 
Following is how the implementation looked like.
public class CountdownTimer : ICountdownTimer
{
#region Private Variable
private bool _Stopped = false;
private TimeSpan _Second = new TimeSpan(0, 0, 1);

private readonly TimeSpan _Interval;
private TimeSpan _TimeRemaining;

private EventHandler _TickedEvent;
private EventHandler _CompletedEvent;
private EventHandler _AbortedEvent;
#endregion

#region Ctor
public CountdownTimer()
{
_Interval = _Second;
}
#endregion

#region ICountdownTimer

event EventHandler ICountdownTimer.Ticked
{
add { _TickedEvent += value; }
remove { _TickedEvent -= value;}
}

event EventHandler ICountdownTimer.Completed
{
add { _CompletedEvent += value; }
remove { _CompletedEvent -= value;}
}

event EventHandler ICountdownTimer.Aborted
{
add { _AbortedEvent += value; }
remove { _AbortedEvent -= value;}
}

public void Start(TimeSpan CountdownTime)
{
_TimeRemaining = CountdownTime;
_Stopped = false;

Device.StartTimer(_Interval, () =>
{
if (this._Stopped)
{
_AbortedEvent?.Invoke(this, EventArgs.Empty);
return false;
}

_TimeRemaining-= _Second;
_TickedEvent?.Invoke(this,new TimerEventArgs { TimeRemaining = _TimeRemaining });

_Stopped = _TimeRemaining.Duration() == TimeSpan.Zero;

if (_Stopped)
_CompletedEvent?.Invoke(this, EventArgs.Empty);

return !_Stopped;
});
}

public void Stop()
{
_Stopped = true;
}
#endregion

One thought on “Simple Timer for Xamarin Forms using Device Timer

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s