Register a background task:
string myTaskName = "Task";
foreach (var cur in BackgroundTaskRegistration.AllTasks)
if (cur.Value.Name == myTaskName)
{
return;
}
await BackgroundExecutionManager.RequestAccessAsync();
BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder
{
Name = "Task",
TaskEntryPoint = "Background.Task"
};
taskBuilder.SetTrigger(new TimeTrigger(15, true));
BackgroundTaskRegistration myFirstTask = taskBuilder.Register();
Background task is created in the Windows Runtime Component as a separate class:
public sealed class Task : IBackgroundTask
{
public async void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
//logic, send http get request, connect to db
deferral.Complete();
}
}
When it is time to perform task- it may run random number of times (1 - 15 times) and then spontaneously terminated and no longer starts,to solve this problem need to re-register task. What could be the reason?
VS show this error when i want run task:
On Windows Phone periodic background tasks are executed at an interval of a minimum of 30 minutes.
(Source: https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh977059.aspx?f=255&MSPPError=-2147217396)
If I were you I'd change the time interval to something more safe (such as 60 minutes) - you can always try smaller intervals later. And take a look at the
oneShot
flag, which is set totrue
in your case. Set it tofalse
to make your task run more than once.Also your exception does not look healthy. You said it even occurs with the background task being empty - you should fix that, just to be safe.
I'd suggest you to manually start and debug your backgorund task a couple of times using the lifecycle feature in Visual Studio. Maybe there are other things that cause your task to die.
But first check the interval.