2017-03-27 54 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