WinJSContrib.BackgroundTasks (NuGet package)

This package simplifies the setup of background tasks in your application.

To start using background tasks, create a new javascript file, for example: "mybackgroundtask.js"
add the following code to the file :

importScripts("//Microsoft.WinJS.2.0/js/base.js");
(function () {
    'use strict';
    var backgroundTaskInstance = Windows.UI.WebUI.WebUIBackgroundTaskInstance.current;
    console.log("Background " + backgroundTaskInstance.task.name + " Starting...");
    function endTask(arg) {
        console.log("Background " + backgroundTaskInstance.task.name + " Ended");
        backgroundTaskInstance.succeeded = true;
        close();
    }
    WinJS.Promise.timeout(1000).done(endTask, endTask);
})();


Within Visual Studio, open the manifest of your application and go to the "declarations" tab. In "available declarations", select "Background Tasks" and click "Add". In "Supported task types", select "System event". In "App settings" fill in the "entry point" field with the path to the javascript file you just created. For example "/js/mybackgroundtask.js". Refer to the MSDN documentation for further information.

In default.html, add a reference to the WinJSContrib library :
<script src="/scripts/winjscontrib/mcnext.bgtask.js"></script>

Now, the background task should be registered at runtime. Within registration, we will provide triggers and conditions to our background task.

Add the following function to default.js

function checkBgTasks() {
    MCNEXT.BgTask.registerTimeTriggerBackgroundTask(
        'js\\mybackgroundtask.js',
        'BgTask',
        [
            //time trigger requires lockscreen notifications, see msdn for more details...
            //new Windows.ApplicationModel.Background.TimeTrigger(60, false), 
            new Windows.ApplicationModel.Background.MaintenanceTrigger(60, false),
            new Windows.ApplicationModel.Background.SystemTrigger(Windows.ApplicationModel.Background.SystemTriggerType.sessionConnected, false),
            new Windows.ApplicationModel.Background.SystemTrigger(Windows.ApplicationModel.Background.SystemTriggerType.internetAvailable, false)
        ],
        [new Windows.ApplicationModel.Background.SystemCondition(Windows.ApplicationModel.Background.SystemConditionType.internetAvailable)]);
}


In the "activated" event, call this function to register your background task.
Please note that background tasks may not work in the Simulator (especially with TimeTrigger)

Last edited Mar 18, 2014 at 9:10 AM by gleborgne, version 2