Search code examples
c#.netuwpwindows-10background-task

Can I set more than one trigger for a BackgroundTask of UWP?


I cannot find in the MSDN documentation if I can set only one trigger (with SetTrigger() method) to a background task or multiple. What if I want to trigger the task on a timer and also programmatically and thus I would need TimerTrigger and ApplicationTrigger? Also is it possible to set multiple conditions with AddCondition()?


Solution

  • A background task registration can only have a single trigger but, you can have several registration for the same background task.

    You can have as many conditions as you want.

    For example, here, MyBackgroundTask is triggered both by a TimeTrigger and an UserPresent triggers when an Internet connection is available. MyBackgroundTask.Run() will be called in both cases.

    public sealed class MyBackgroundTask : IBackgroundTask
    {
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            // your task code here
        }
    
        public void Register()
        {
             RegisterWithTrigger(BackgroundTaskSuffixTime,          new TimeTrigger((uint) RefreshInterval.TotalMinutes, false));
             RegisterWithTrigger(BackgroundTaskSuffixUserPresent,   new SystemTrigger(SystemTriggerType.UserPresent, false));
        }
    
        private static IBackgroundTaskRegistration RegisterWithTrigger(string taskSuffix, IBackgroundTrigger trigger)
        {
            var taskEntryPoint  = typeof(MyBackgroundTask).FullName;
            var taskName        = taskEntryPoint + taskSuffix;
    
            var registration            = BackgroundTaskRegistration.AllTasks.Select(x => x.Value).FirstOrDefault(x => x.Name == taskName);
            if(registration != null) return registration;
    
            var taskBuilder             = new BackgroundTaskBuilder();
            taskBuilder.Name            = taskName;
            taskBuilder.TaskEntryPoint  = taskEntryPoint;
            taskBuilder.SetTrigger(trigger);
            taskBuilder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable));
            return taskBuilder.Register();
        }
    }
    

    Do not forget to declare all the appropriate triggers in the application manifest:

    <Extension Category="windows.backgroundTasks" EntryPoint="Background.MyBackgroundTask">
      <BackgroundTasks>
        <Task Type="systemEvent" />
        <Task Type="timer" />
      </BackgroundTasks>
    </Extension>