Skip to content Skip to sidebar Skip to footer

Android Scheduled Timer - Mono For Android Or Java

I need to run a method every 5 seconds using Mono for Android. Is there a scheduled timer in Android? I have tried this code, however, it fails to start: using System; using System

Solution 1:

I had the same problem, I had to start a service after a certain time.

        DateTime dt = DateTime.Now;
        t1 = new System.Timers.Timer(200);
        t1.Elapsed += new ElapsedEventHandler(OnTimeEvent);
        t1.Interval = 4000;
        t1.Enabled = true;
        t1.Start();
    }
    privatevoidOnTimeEvent(object source, ElapsedEventArgs e)
    {
        RunOnUiThread(delegate
        {
      //this is my service which i was starting at every 4 seconds  
            StartService(new Intent(this, typeof(ServiceClass)));  
        });
    }

Solution 2:

Why not just use System.Timers.Timer?

var timer = new Timer();
//What to do when the time elapses
timer.Elapsed += (sender, args) => FireTheMissiles();
//How often (5 sec)
timer.Interval = 5000;
//Start it!
timer.Enabled = true;

privatevoidFireTheMissiles()
{
    //But I'm le tired...
}

Another approach to make a new Task or Thread and let it sleep for 5 seconds every time:

Task.Factory.StartNew(() =>
    {
        while (true)
        {
            // do some stuffThread.Sleep(TimeSpan.FromSeconds(5));
        }
    });

ThreadPool.QueueUserWorkItem(thread =>
    {
        while (true)
        {
            // do some stuffThread.Sleep(TimeSpan.FromSeconds(5));
        }
    });

Post a Comment for "Android Scheduled Timer - Mono For Android Or Java"