Share via


Quickstart: Create and register a background task (HTML)

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

This topic discusses how to create and register a background task worker for your app.

Prerequisites

  • Have an app that you're ready to provide a background task.

Create the Background Task class

Create a separate method with the code that runs in the background. This code will run when a specific event is triggered. Read SystemTrigger and MaintenanceTrigger for a list of trigger types that can be used by any app.

The following steps show you how to write a background task worker that uses Windows.UI.WebUI.WebUIBackgroundTaskInstance. Before getting started, create a new empty JavaScript file in Microsoft Visual Studio.

  1. Create a new JavaScript file in your project. The functions and code in this file are what will run in the background.

    The following skeleton code can help you get started:

    
    //
    // A JavaScript background task is specified in a .js file. The name of the file is used to
    // launch the background task.
    //
    (function () {
        "use strict";
    
        //
        // This var is used to get information about the current instance of the background task.
        //
        var backgroundTaskInstance = Windows.UI.WebUI.WebUIBackgroundTaskInstance.current;
    
    
        //
        // This function will do the work of your background task.
        //
        function doWork() {
            var key = null,
                settings = Windows.Storage.ApplicationData.current.localSettings;
    
            // Write JavaScript code here to do work in the background.
    
    
            //
            // Record information in LocalSettings to communicate with the app.
            //
            key = backgroundTaskInstance.task.taskId.toString();
            settings.values[key] = "Succeeded";
    
            //
            // A JavaScript background task must call close when it is done.
            //
            close();
        }
    
        doWork();
    
    })();
    
  2. A background task should recognize when it's asked to stop work. First, add an event listener for the "canceled" event and add a variable named "canceled" to signal the background task.

    The background task sample listens to the "canceled" event with the onCanceled functions:

        var cancel = false;
    
        //
        // Associate a cancellation handler with the background task.
        //
        function onCanceled(cancelSender, cancelReason) {
            cancel = true;
        }
        backgroundTaskInstance.addEventListener("canceled", onCanceled);
    

    Then, modify your code to stop work and close if canceled is set to true.

    The background task sample creates a task called SampleBackgroundTask:

    
    //
    // A JavaScript background task is specified in a .js file. The name of the file is used to
    // launch the background task.
    //
    (function () {
        "use strict";
    
        //
        // This var is used to get information about the current instance of the background task.
        //
        var backgroundTaskInstance = Windows.UI.WebUI.WebUIBackgroundTaskInstance.current;
    
    
        //
        // This function will do the work of your background task.
        //
        function doWork() {
            var key = null,
                settings = Windows.Storage.ApplicationData.current.localSettings;
    
            //
            // TODO: Write your JavaScript code here to do work in the background.
            // If you write a loop or callback, remember  have it check for canceled==false.
            //
    
            //
            // Record information in LocalSettings to communicate with the app.
            //
            key = backgroundTaskInstance.task.taskId.toString();
            settings.values[key] = "Succeeded";
    
            //
            // A JavaScript background task must call close when it is done.
            //
            close();
        }
    
        if (!canceled) {
            doWork();
        } else {
            //
            // Record information in LocalSettings to communicate with the app.
            //
            key = backgroundTaskInstance.task.taskId.toString();
            settings.values[key] = "Canceled";
    
            //
            // A JavaScript background task must call close when it is done.
            //
            close();
        }
    
    })();
    
  3. Ensure that your background task calls the built-in close() method every time it completes work or is cancelled. If the background task doesn't close itself, the background task's process can continue to exist, consuming memory and battery life even though the background task is done.

    Call close() whenever a JavaScript background task completes work or is cancelled:

    
    close();
    

The following steps involve adding code to your existing app (for example, "default.js").

Note  You can also create a function dedicated to registering background tasks - see How to register a background task. In that case, instead of using the next 3 steps, you can simply construct the trigger and provide it to the registration function along with the task name, task entry point, and (optionally) a condition.

 

Register the background task

  1. Find out if the background task is already registered by iterating through the BackgroundTaskRegistration.allTasks property. This step is important; if your app doesn't check for existing background task registrations, it could easily register the task multiple times, causing issues with performance and maxing out the task's available CPU time before work can complete.

    The following example iterates on the allTasks property and sets a flag variable to true if the task is already registered:

    var taskRegistered = false;
    var exampleTaskName = "Example background task worker name";
    
    var background = Windows.ApplicationModel.Background;
    var iter = background.BackgroundTaskRegistration.allTasks.first();
    
    while (iter.hasCurrent) {
    
        var task = iter.current.value;
    
        if (task.name === exampleTaskName) {
    
            taskRegistered = true;
            break;
        }
    
        iter.moveNext();
    }
    
  2. If it is not already registered, register the background task by calling the register function, passing in the background task file name and a SystemTrigger.

    The background task trigger controls when the background task will run. See SystemTrigger for a list of possible system triggers.

    
    if (taskRegistered != true) {
    
        var builder = new Windows.ApplicationModel.Background.BackgroundTaskBuilder();
    
        var trigger = new Windows.ApplicationModel.Background.SystemTrigger(Windows.ApplicationModel.Background.SystemTriggerType.timeZoneChange, false);
    
        builder.name = exampleTaskName;
        builder.taskEntryPoint = "js\\ExampleBackgroundTask.js";
        builder.setTrigger(trigger);
    
        var task = builder.register();
    }
    
  3. You can add a condition to control when your task will run after the trigger event occurs (optional). For example, if you don't want the task to run until the user is present, use the condition UserPresent. For a list of possible conditions, see SystemConditionType.

    Note  

    Starting in Windows 8.1, background task registration parameters are validated at the time of registration. An error is returned if any of the registration parameters are invalid. Your app must be able to handle scenarios where background task registration fails - for example, use a conditional statement to check for registration errors and then retry failed registration using different parameter values.

     

    if (taskRegistered != true) {
    
        var builder = new Windows.ApplicationModel.Background.BackgroundTaskBuilder();
    
        var trigger = new Windows.ApplicationModel.Background.SystemTrigger(Windows.ApplicationModel.Background.SystemTriggerType.timeZoneChange, false);
    
        builder.name = exampleTaskName;
        builder.taskEntryPoint = "js\\ExampleBackgroundTask.js";
        builder.setTrigger(trigger);
    
        builder.addCondition(new Windows.ApplicationModel.Background.SystemCondition(Windows.ApplicationModel.Background.SystemConditionType.userPresent));
    
        var task = builder.register();
    }
    

    Note  

    For Windows Phone Store apps, you must call RequestAccessAsync before attempting to register any background task. On Windows, this call is only required for the set of background tasks that require your app to be on the lock screen to run, but on the phone you must call this method once before registering any background task.

    To ensure that your Windows Phone app continues to run properly after you release an update, you must call RemoveAccess and then call RequestAccessAsync when your app launches after being updated. For more information, see Guidelines for background tasks (HTML).

Handle background task completion

Your app can observe progress and completion of the background task by registering for the "completed" event listener every time the app is activated.

  1. Write a function that your app can use to recognize background worker completion.

    The background task sample adds a function called onCompleted:

    
    //
    // Handle background task completion.
    //
    "completeHandler": function (task) {
        this.onCompleted = function (args) {
            try {
                var key = task.taskId;
                var settings = Windows.Storage.ApplicationData.current.localSettings;
                var status = settings.values[key];
    
                switch (task.name) {
                    case BackgroundTaskSample.sampleBackgroundTaskName:
                        BackgroundTaskSample.sampleBackgroundTaskStatus = status;
                        SampleBackgroundTask.updateUI();
                        break;
                    case BackgroundTaskSample.sampleBackgroundTaskWithConditionName:
                        BackgroundTaskSample.sampleBackgroundTaskWithConditionStatus = status;
                        SampleBackgroundTaskWithCondition.updateUI();
                        break;
                    case BackgroundTaskSample.servicingCompleteTaskName:
                        BackgroundTaskSample.servicingCompleteTaskStatus = status;
                        ServicingComplete.updateUI();
                        break;
                    case BackgroundTaskSample.javaScriptBackgroundTaskName:
                        BackgroundTaskSample.javaScriptBackgroundTaskStatus = status;
                        JavaScriptBackgroundTask.updateUI();
                        break;
                    case BackgroundTaskSample.timeTriggerTaskName:
                        BackgroundTaskSample.timeTriggerTaskStatus = status;
                        TimeTriggerBackgroundTask.updateUI();
                        break;
                }
            } catch (ex) {
                //WinJS.log && WinJS.log(ex, "sample", "status");
            }
        };
    }
    
  2. Subscribe to the "completed" event listener with the function.

    The background task sample adds onCompleted to the "completed" event:

    
    task.addEventListener("completed", new BackgroundTaskSample.completeHandler(task).onCompleted);
    

Declare that your app uses background tasks in the app manifest

Before your app can actually register background tasks, you must declare each background task (and the triggers it uses) in the app manifest.

  • Open the app manifest and go to the Extensions element. Add an Extension element, with category set to "windows.backgroundTasks", for each background task class used in your app. You must list each type of trigger that background task uses - your app won't be able to register the background task with an undeclared trigger type.

    The background task sample registers three background task workers:

    
    <Extension Category="windows.backgroundTasks" StartPage="js\backgroundtask.js">
      <BackgroundTasks>
        <Task Type="systemEvent" />
      </BackgroundTasks>
    </Extension>
    <Extension Category="windows.backgroundTasks" EntryPoint="Tasks.SampleBackgroundTask">
      <BackgroundTasks>
        <Task Type="systemEvent" />
        <Task Type="timer" />
      </BackgroundTasks>
    </Extension>
    <Extension Category="windows.backgroundTasks" EntryPoint="Tasks.ServicingComplete">
      <BackgroundTasks>
        <Task Type="systemEvent" />
      </BackgroundTasks>
    </Extension>
    

Summary

You should now understand the basics of how to write a background task class, how to register the background task from within your app, and how to make your app recognize when the background task is complete. You should also understand how to update the application manifest so that the OS will let your app register the background tasks.

Note  You can download the background task sample to see these code examples (and more) in the context of a complete and robust JavaScript app that uses background tasks.

 

Detailed background task instructional topics

How to respond to system events with background tasks

How to register a background task

How to set conditions for running a background task

How to use maintenance triggers

How to handle a cancelled background task

How to monitor background task progress and completion

How to run a background task on a timer

Background task guidance

Guidelines and checklists for background tasks

How to debug a background task

How to trigger suspend, resume, and background events in Windows Store apps (when debugging)

Background Task API Reference

Windows.ApplicationModel.Background