簡體   English   中英

如何在 Xamarin Forms 中每隔 x 秒調用一個方法 x 時間?

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

我正在 Xamarin Forms 中提出一個應用程序,其中我需要每 x 時間調用一個方法 x 時間(例如每 5 秒 2 分鍾)。 怎么做到呢?

我只找到了有關如何每 x 次調用一個方法的信息,但這對於我正在尋找的內容來說還不夠。

這是我嘗試過的。 這會在 15 秒后調用MyMethod

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

這每 5 秒調用一次MyMethod

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

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

我需要的是在 x 秒內每 x 秒調用一次MyMethod

別忘了 Xamarin 是基於 C# 語言的,所以你可以使用 C# 語言。

根據 Microsoft 文檔Timer class ,您可以執行以下操作:

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
    }
}

你可以這樣做:

您可能需要一個在后台運行的線程:

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);
        }
    });
}

您可以為計時器設置限制秒數。

例如,您希望每 5 秒執行一次操作,持續 2 分鍾。

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();

            }
        });
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM