Forum Xamarin Xamarin.Android

How can i run a timer in the background

Hello,

i want a timer, that runs in the background. After about 10 seconds the timer should stop tasks or update my Layout. How can I do this?

Thanks

Tagged:

Answers

  • HorstKirchbergHorstKirchberg USMember ✭✭

    Sorry,

    that is not what i'm searching for. I need a background timer during the user is working with the app.

  • StefaanAvonds.3725StefaanAvonds.3725 USMember ✭✭✭

    @HorstKirchberg

    I don't know if this is still an open topic, but you can create a timer task of your own.

    Create an extension method on "TaskFactory"

            /// <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>
            public static Task StartNewTaskContinuously(this TaskFactory taskFactory, Action action, CancellationToken cancellationToken, TimeSpan timeSpan)
            {
                return taskFactory.StartNew(async () =>
                {
                    while (!cancellationToken.IsCancellationRequested)
                    {
                        action();
    
                        await Task.Delay(timeSpan);
                    }
                });
            }
    

    Now all you have to do is call this method the same way you start another Task:

                CancellationToken token = _cancellationSource.Token;
    
                Task.Factory.StartNewTaskContinuously(() =>
                {
                    // Do stuff
                },
                token,
                TimeSpan.FromSeconds(2));
    

    Maybe there are better solutions (if so, please let me know) but this worked for me.

Sign In or Register to comment.