Junpei Kun
Junpei Kun

Reputation: 693

How to run some code every day at midnight in background in UWP?

I think the title is self explanatory: I struggle to fire a background task every day, at midnight for example. The task is registered properly with a TimeTrigger, added to the Manifest but the result varies, sometimes it fires only on phone, sometimes only on PC, othertimes it won't at all.

Please tell me what is the proper way of doing it. I finished everything in my app except this.

Thanks in advance.

Edit: the way I do it now is using 2 background tasks: each one uses a TimeTrigger, the first one is set to run once at midnight and its only use is to schedule the second one to run every 24 hours. But as I said earlier, it doesn't work as expected.

Upvotes: 4

Views: 1200

Answers (1)

Mamoru Satoh
Mamoru Satoh

Reputation: 2710

OS can cancel/terminate the background task WITH or WITHOUT the notification. For example... If you regist a 15min-intervaled bgtask and implement the task cancellation, you may see that the task is cancelled several times within a day.

My recommendation is ... Try to run the bgtask several times within the 'midnight' to workaround the task cancellation.

  1. Implement the cancellation at your bgtask.
  2. Regist your task with 1hr interval.
  3. At beginning of the task, check the time and flag, and do the task if the time is 'midnight' and the flag is not set.
  4. Set the 'done' flag at localsettings.

Details of background cancellation is here. https://msdn.microsoft.com/en-us/windows/uwp/launch-resume/handle-a-cancelled-background-task

And this my answer may helps you Timetrigger not firing backgroundtask UWP

Here is a my implementation of bgtask. It's support the cancellation.

    public async void Run(IBackgroundTaskInstance taskInstance)
    {
        string dbgout = "";
        var startTime = DateTime.Now;
        dbgout += "BgTask ";

        var cost = BackgroundWorkCost.CurrentBackgroundWorkCost;
        var cancel = new System.Threading.CancellationTokenSource();
        taskInstance.Canceled += (s, e) =>
        {
            dumpLog("Canceled.");
            cancel.Cancel();
            cancel.Dispose();
        };


        try
        {
            _deferral = taskInstance.GetDeferral();

            dbgout += cost.ToString() + " ";

            switch (cost)
            {
                case BackgroundWorkCostValue.Low:
                case BackgroundWorkCostValue.Medium:
                    await TimeConsumedTaskLowMidAsync().AsTask(cancel.Token);
                    break;
                case BackgroundWorkCostValue.High:
                    await TimeConsumedTaskHighAsync().AsTask(cancel.Token);
                    break;
                default:
                    break;
            }

        }
        catch (Exception e)
        {
            dbgout += ("Failed " + e.Message + "...");
        }
        finally
        {
            dumpLog(dbgout + " " + (DateTime.Now - startTime).TotalSeconds.ToString("F1"));
            _deferral.Complete();
        }

    }

Upvotes: 3

Related Questions