Search code examples
c#windows-10uwpbackground-task

Run Background Task at specific time - Windows 10 App


I've searched a way to run a Background Task daily at a specific time, e.x. at at 12:00.

I've registered the BackgroundTask with a TimeTrigger, which unfortunately starts immediately after registering.

builder.SetTrigger(new TimeTrigger(24 * 60, false));

Is there a easier way, then checking every hour, if this is the right time of day?


Solution

  • Microsoft seems to avoid apps from triggering at a precise time, but you might be able to get close by calculating the number of minutes from the time the user registers the task to 12:00, then resubscribe another task from there set for 24*60 as you have. I'm unsure if Microsoft allows this within a Background task, but it's worth a shot.

    Example of calculating the minutes to midnight for the task

    var tommorowMidnight = DateTime.Today.AddDays(1);
    var timeTilMidnight = tommorowMidnight - DateTime.Now;
    var minutesTilMidnight = (uint)timeTilMidnight.TotalMinutes;
    builder.SetTrigger(new TimeTrigger(minutesTilMidnight, true));