简体   繁体   中英

How to call a method every x seconds for x time in Xamarin Forms?

I am making an application in Xamarin Forms in which I need to call a method every x time for x time (eg every 5 seconds for 2 minutes). How can it be done?

I have only found information on how to call a method every x time, but this is not enough for what I am looking for.

This is what I have tried. This calls MyMethod after 15 seconds have elapsed:

await Task.Delay(new TimeSpan(0, 0, 15)).ContinueWith(async o =>
{
    MyMethod();
});

And this calls MyMethod every 5 seconds:

var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromSeconds(5);

var timer = new System.Threading.Timer((e) =>
{
    MyMethod();
}, null, startTimeSpan, periodTimeSpan);

What I need is to call MyMethod every x seconds for x amount of time.

Don't forget that Xamarin is based on C# language, so you can use C# language.

According to Microsoft documentation Timer class , you can do something like this:

public class Example
{
     private static System.Timers.Timer aTimer;

    public static void Main()
    {
       SetTimer();
    }
     
    private static void SetTimer()
    {
       // Create a timer with a five second interval.
       aTimer = new System.Timers.Timer(5000);
       // Hook up the Elapsed event for the timer. 
       aTimer.Elapsed += OnTimedEvent;
       aTimer.AutoReset = true;
       aTimer.Enabled = true;
    }

    private static void OnTimedEvent(Object source, ElapsedEventArgs e)
    {
        // Do your instruction while two minutes here
        // You could create another Timer which repeat instruction during two minutes
    }
}

You could do something like this:

You'll probably need a Thread that is running in the background:

private async void CallMethodEveryXSecondsYTimes(int waitSeconds, int durationSeconds) 
{
    await Task.Run(() => {
        var end = DateTime.Now.AddSeconds(durationSeconds);
        while (end > DateTime.Now)
        {
                Dispatcher.BeginInvokeOnMainThread(() =>
                {
                    YourMethod();
                });
                Thread.Sleep(waitSeconds*1000);
        }
    });
}

You could set a limit seconds for the Timer.

For example you want do something every 5 seconds for 2 minutes.

int sec = 120000; // 2 minutes
int period = 5000; //every 5 seconds

TimerCallback timerDelegate = new TimerCallback(Tick);
Timer _dispatcherTimer = new System.Threading.Timer(timerDelegate, null, period, period);// if you want the method to execute immediately,you could set the third parameter to null

private void Tick(object state)
    {

        Device.BeginInvokeOnMainThread(() =>
        {
            sec -= period;
       
            if (sec >= 0)
            {
                //do something
            }
            else
            {
                _dispatcherTimer.Dispose();

            }
        });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM