Harshita Ghosh
Harshita Ghosh

Reputation: 93

How to run a timer in background in xamarin forms?

In my app I want to set a timer to calculate the working time. My timer is working fine but when I switch to another page then it stops working. How to run the timer and calculate total time run in the background. Here is my code

Stopwatch st = new Stopwatch();

private void WorkClockStart(object sender,EventArgs e)
{
    if(LaborClock.Text == "Start Work Clock")
    {
        LaborClock.Text = "Stop Work Clock";

        Device.StartTimer(TimeSpan.FromMilliseconds(1), () =>
        {
            st.Start();
            return false;
        });
    }
    else
    {
        st.Stop();
        long elapsed = st.ElapsedMilliseconds;
        var sec = elapsed / 1000;
        DisplayAlert("Message", "Worked Time(Sec): " + sec, "ok");
        LaborClock.Text = "Start Work Clock";
        st.Reset();
    } 
}

How to achieve this in Xamarin.Forms?

Upvotes: 1

Views: 5625

Answers (2)

Yuvraj Patil
Yuvraj Patil

Reputation: 1

I agree with Daniel you can use DateTime and Task.Factory.StartNew, Like the below code.

Task.Factory.StartNew( async() =>
                        {
                                var time = DateTime.Now;
                                var counter = 30;
                                transactionItem.RetryCount = 30;
                                do
                                {
                                    await Task.Delay(1000);
                                    counter = Math.Abs((DateTime.Now - time.AddSeconds(29)).Seconds);

                                 } while (counter != 0 && time.AddSeconds(29) > DateTime.Now);
                        });

Upvotes: 0

Daniel
Daniel

Reputation: 9521

Why do you use a timer? Just store the DateTime.Now in a variable when you start your watch and compute the delta with DateTime.Now when you stop it. Then you can store wherever you want (in a static variable for example or in App.cs if you want depending on your requirement)

Upvotes: 4

Related Questions