How Do I Add A Timer In Xamarin?
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 yo
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 herereturntrue; // 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:
publicsealedclassTimer : CancellationTokenSource {
privatereadonly Action _callback;
privateint _millisecondsDueTime;
privatereadonlyint _millisecondsPeriod;
publicTimer(Action callback, int millisecondsDueTime) {
_callback = callback;
_millisecondsDueTime = millisecondsDueTime;
_millisecondsPeriod = -1;
Start();
}
publicTimer(Action callback, int millisecondsDueTime, int millisecondsPeriod) {
_callback = callback;
_millisecondsDueTime = millisecondsDueTime;
_millisecondsPeriod = millisecondsPeriod;
Start();
}
privatevoidStart() {
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();
}
}
});
}
publicvoidStop() {
Cancel();
}
protectedoverridevoidDispose(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:
privateint i;
final Timer timer=newTimer();
TimerTask task=newTimerTask() {
@Overridepublicvoidrun() {
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)]
publicclassMainActivity : Activity
{
protectedoverridevoidOnCreate(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);
}
}
classMyTask : TimerTask
{
Timer mTimer;
publicMyTask(Timer timer) {
this.mTimer = timer;
}
int i;
publicoverridevoidRun()
{
if (i < 60)
{
i++;
}
else {
mTimer.Cancel();
}
Android.Util.Log.Error("time",i+"");
}
}
Solution 4:
You can always use
Task.Factory.StartNewTaskContinuously(YourMethod, new CancellationToken(), TimeSpan.FromMinutes(10));
Be sure to add the following class to your project
staticclassExtensions
{
///<summary>/// Start a new task that will run continuously for a given amount of time.///</summary>///<param name="taskFactory">Provides access to factory methods for creating System.Threading.Tasks.Task and System.Threading.Tasks.Task`1 instances.</param>///<param name="action">The action delegate to execute asynchronously.</param>///<param name="cancellationToken">The System.Threading.Tasks.TaskFactory.CancellationToken that will be assigned to the new task.</param>///<param name="timeSpan">The interval between invocations of the callback.</param>///<returns>The started System.Threading.Tasks.Task.</returns>publicstatic Task StartNewTaskContinuously(this TaskFactory taskFactory, Action action, CancellationToken cancellationToken, TimeSpan timeSpan
, string taskName = "")
{
return taskFactory.StartNew(async () =>
{
if (!string.IsNullOrEmpty(taskName))
{
Debug.WriteLine("Started task " + taskName);
}
while (!cancellationToken.IsCancellationRequested)
{
action();
try
{
await Task.Delay(timeSpan, cancellationToken);
}
catch (Exception e)
{
break;
}
}
if (!string.IsNullOrEmpty(taskName))
{
Debug.WriteLine("Finished task " + taskName);
}
});
}
}
Post a Comment for "How Do I Add A Timer In Xamarin?"