2017-03-27 53 views
0

我目前正在开发一个应用程序,后台任务应该在用户设置的时间开启。例如,用户选择'01:45PM',该应用正在计算从现在到该时间的分钟数,并且使用时间触发器注册后台任务。不幸的是,背景任务根本没有开火。有时它在我启动计算机后才被解雇。我很感激任何意见,因为我一个星期以来无法解决这个问题。UWP后台任务计时器没有开火

我已经调试通过VisualStudio启动它的后台任务,所以问题不在BackgroundTask.cs文件中。

这里是我的代码:

  • 注册后台任务:

    //I set the time to 15 minutes to see if this would work. It didn't... 
    var trigger = new TimeTrigger(15, true); 
    BackgroundTaskHelper.RegisterBackgroundTask("BackgroundTask.BackgroundTask", "BackgroundTask", trigger, null); 
    
  • 方法注册后台任务:

    public static async void RegisterBackgroundTask(string taskEntryPoint, string taskName, IBackgroundTrigger trigger, IBackgroundCondition condition) 
    { 
        foreach (var cur in BackgroundTaskRegistration.AllTasks) 
        { 
         if (cur.Value.Name == taskName) 
         { 
          cur.Value.Unregister(true); 
         } 
        }    
        var builder = new BackgroundTaskBuilder(); 
        builder.Name = taskName; 
        builder.TaskEntryPoint = taskEntryPoint; 
        builder.SetTrigger(trigger); 
    
        if (condition != null) 
        { 
         builder.AddCondition(condition); 
        } 
    
        await BackgroundExecutionManager.RequestAccessAsync(); 
        var task = builder.Register(); 
    } 
    
  • Package.appxmanifest Package.appxmanifest, Image

感谢您的帮助!

+0

可能有很多问题。我经常想到两件很常见的问题:后台任务运行多长时间(超过30秒是标准BGTask的问题),其次是:此任务的CPU使用率有多高,CPU的使用率有多高用法,什么时候应该运行?这也许是有帮助的:https://docs.microsoft.com/en-us/windows/uwp/launch-resume/debug-a-background-task – user3079834

+0

目前它只是发送一个Toast通知,所以持续时间少于30秒,CPU使用率很低。 – MadMax

+0

并且它在烧制时的CPU使用率?因为有时任务不会触发,如果主机的CPU使用率很高。 – user3079834

回答

0

创建一个新的TimeTrigger。第二个参数OneShot指定后台任务是仅运行一次还是保持定期运行。如果OneShot设置为true,则第一个参数(FreshnessTime)指定调度后台任务之前等待的分钟数。如果OneShot设置为false,则FreshnessTime指定background task将运行的频率。

如果FreshnessTime设置为15分钟,并且OneShot为true,则该任务将计划在注册后15到30分钟之间开始运行一次。如果它设置为25分钟并且OneShot为真,则该任务将被计划在从注册25到40分钟之后开始运行一次。因此,TimeTrigger不适合您的情况。在Windows 10 UWP中,警报只是Toast通知与“警报”方案。并且要在特定时间发出警报,您可以使用计划的Toast通知。

以下代码是如何安排闹铃在特定时间出现。详情请参考Quickstart: Sending an alarm in Windows 10。附带的sample application是一个简单的快速入门报警应用程序。

DateTime alarmTime = DateTime.Now.AddMinutes(1); 

// Only schedule notifications in the future 
// Adding a scheduled notification with a time in the past 
// will throw an exception. 
if (alarmTime > DateTime.Now.AddSeconds(5)) 
{ 
    // Generate the toast content (from previous steps) 
    ToastContent toastContent = GenerateToastContent(); 

    // Create the scheduled notification 
    var scheduledNotif = new ScheduledToastNotification(
     toastContent.GetXml(), // Content of the toast 
     alarmTime // Time we want the toast to appear at 
     ); 

    // And add it to the schedule 
    ToastNotificationManager.CreateToastNotifier().AddToSchedule(scheduledNotif); 
} 
+0

谢谢!这非常有趣!在预定时间之后是否有可能获得内容?我想在预定的时间检查网页内容,并向本网页的部分内容发送敬酒通知。有什么方法可以在这个时候动态获取内容? – MadMax