Background Task: Timer trigger

In continuation with the previous article: Background tasks: network change trigger

Continuing our previous tutorial, this time we are going to cover how to invoke background tasks based on a timer.

TIMER TRIGGER:

The Timer Trigger will fire at a specified interval to enable your app to perform some work. In this particular example we will simply display the date and time and some text on the tile to be updated after the specified interval by the time trigger has elapsed.

Steps:

Follow the following steps to learn how to use the timer trigger:

For detailed steps, visit: Background tasks: network change trigger

  • Create a new C# windows store project and name it as the timerBackgroundTask.
  • After the project opens, right click the solution node in the solution explorer and select (1) Add (2) New Project, and then select windows runtime component named as BackgroundTasks and add reference to it through the references tab in the solution explorer.
  • Now your solution would have a class named as Class1. Rename the class as BackgroundTasks and implement the task as shown below
01.public sealed  class MyBackgroundTask : IBackgroundTask
02. 
03.{
04. 
05.    public void  Run(IBackgroundTaskInstance taskInstance)
06. 
07.    {
08. 
09.      UpdateStatusAndTime();
10. 
11.    }
12. 
13.  
14. 
15.    private void  UpdateStatusAndTime()
16. 
17.    {
18. 
19.      var tileContent = TileUpdateManager.GetTemplateContent(
20. 
21.      TileTemplateType.TileSquareText03);
22. 
23.      var tileLines = tileContent.SelectNodes("tile/visual/binding/text");
24. 
25.      tileLines[0].InnerText = “30 minutes elapsed. Updating the tile”;
26. 
27.            
28. 
29.      tileLines[1].InnerText =          DateTime.Now.ToString("MM/dd/yyyy");
30. 
31.      tileLines[2].InnerText = DateTime.Now.ToString("HH:mm:ss");
32. 
33.  
34. 
35.      var notification = new  TileNotification(tileContent);
36. 
37.  
38. 
39.      var updater =  TileUpdateManager.CreateTileUpdaterForApplication();
40. 
41.      updater.Update(notification);
42. 
43.  
44. 
45.    }
46. 
47.}

LOCK SCREEN:

  • Before attempting to register this Task, you must first request the user to give permission to this app to be placed on the lock screen.
  •  A user can place up to seven apps on his lock screen. Once an app is added to the lock screen, it gets a higher priority over other apps. This higher priority has a direct effect on background tasks.
  • The Windows 8.1 lock screen provides “at a glance” information to users. It is possible for apps to present their own information on the lock screen. If your app has summary information that changes in real time, it may be a candidate for the lock screen. Example lock screen information includes upcoming appointments, current weather conditions, recent emails, and message alerts.
  • Use the following code for requesting the lock screen capability
1.BackgroundExecutionManager.RequestAccessAsync();

Note: An app is allowed to ask for lock screen access only once. The user can choose only one of the two options, so their preference will have been stated. Further calls to RequestAccessAsync will be ignored.

REGISTERING THE BACKGROUND TASK:

01.protected override  void OnNavigatedTo(NavigationEventArgs e)
02. 
03.{
04. 
05.  var builder = new  BackgroundTaskBuilder();
06. 
07.  builder.Name = "MySampleTask";
08. 
09.  builder.TaskEntryPoint = "BackgroundTasks.MyBackgroundTask";
10. 
11.  builder.SetTrigger(new TimeTrigger(30, false));
12. 
13.  var ret = builder.Register();
14. 
15.}

Open the MainPage.xaml.cs class from your solution and add the following code in its OnNavigatedTo event.

For detailed information on how to register a background task, see: Registering background tasks

  • The TimeTrigger method used in the SetTrigger method has two parameters, the first one, called as FreshnessTime specifies the number of minutes to be wait before running the task . The second parameter, called as OneShot has two possible values i.e. true and false. A value of true indicates it should only be called once, and a value of false indicates it is recurring and should be called repeatedly.
  • Windows has a built-in timer that runs background tasks in 15-minute intervals. Note that on Windows Phone, the interval is 30 minutes. If FreshnessTime is set to less than 15 minutes, an exception is thrown when attempting to register the background task.
  • You can also add a condition if need be. For example, if your app is fetching data from the internet after every 1 hour, then you can specifically enforce a condition that if there is not internet access, the background task should not be called. For more information on conditions see: Conditions on background tasks

DECLARATION OF THE TASK IN APP MANIFEST:      

Open the app manifest from your project’s solution, select background tasks from the available declarations and click add. In the supported task types, select Timer and in the app settings, use the entry point property and set it to the full path of the IBackgroundTask implementation.

Run the application by pressing F5.

HOW TO TRIGGER THE TIMER EVENT:

After running the application, you wouldn’t see anything on the screen since we haven’t added any UI elements in the MainPage.xaml. However, in this case you need to be more concerned with the app’s tile. Pin the tile of the app on the start screen if it isn’t already pinned. You will see a cross as a tile since we didn’t add any visual assets.

If everything goes well, your tile would be updated after half an hour.

That’s all for this tutorial. Happy Coding!