Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I cancel from Device.StartTimer?

When I use System.Threading.Timer I can stop my timer and start it again:

protected override void OnScrollChanged(int l, int t, int oldl, int oldt)
{
    if (timer == null)
    {
        System.Threading.TimerCallback tcb = OnScrollFinished;
        timer = new System.Threading.Timer(tcb, null, 700, System.Threading.Timeout.Infinite);
    }
    else
    {
        timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
        timer.Change(700, System.Threading.Timeout.Infinite);
    }
}

What is the best way to stop Device.StartTimer and start it again?

like image 828
Kirill Avatar asked Aug 31 '15 05:08

Kirill


1 Answers

I am guessing you are referring to Device.StartTime in XamarinForms. The way to stop or continue a recurring task is determined by what the second argument returns:

// run task in 2 minutes
Device.StartTimer(TimeSpan.FromMinutes(2), () =>
{
    if (needsToRecur)
    {
        // returning true will fire task again in 2 minutes.
        return true;
    }

    // No longer need to recur. Stops firing task
    return false; 
});

If you want to temporarily stop this timer, and then fire it again after some time, you will have to call Device.StartTimer again. It would be nice to wrap this into its own class where you can use a private member to determine if a continuous task is still running. Something like this:

public class DeviceTimer
{
  readonly Action _Task;
  readonly List<TaskWrapper> _Tasks = new List<TaskWrapper>();
  readonly TimeSpan _Interval;
  public bool IsRecurring { get; }
  public bool IsRunning => _Tasks.Any(t => t.IsRunning);

  public DeviceTimer(Action task, TimeSpan interval, 
    bool isRecurring = false, bool start = false)
  {
    _Task = task;
    _interval = interval;
    IsRecurring = isRecurring;
    if (start)
      Start();
  }

  public void Restart()
  {
    Stop();
    Start();
  }

  public void Start()
  {
    if (IsRunning)
      // Already Running
      return;

    var wrapper = new TaskWrapper(_Task, IsRecurring, true);
    _Tasks.Add(wrapper);

    Device.StartTimer(_interval, wrapper.RunTask);
  }

  public void Stop()
  {
    foreach (var task in _Tasks)
      task.IsRunning = false;
    _Tasks.Clear();
  }


  class TaskWrapper
  {
    public bool IsRunning { get; set; }
    bool _IsRecurring;
    Action _Task;
    public TaskWrapper(Action task, bool isRecurring, bool isRunning)
    {
      _Task = task;
      _IsRecurring = isRecurring;
      IsRunning = isRunning;
    }

    public bool RunTask()
    {
      if (IsRunning)
      {
        _Task();
        if (_IsRecurring)
          return true;
      }

      // No longer need to recur. Stop
      return IsRunning = false;
    }
  }         
}
like image 189
harsimranb Avatar answered Nov 11 '22 02:11

harsimranb