locked
Background task of time trigger event.it is not working.

    Question

  • I write a script about background task of time trigger event, But it is not working.

    background task is registered, but 15 mins after script not run to CompleteHandler function.

    The background task use SystemTriggerType,it will working.

    backgroundService.js

    (function () {
    
        var backgroundTaskName = "ChinaWeatherBackgroundTask";
        var backgroundTaskEntryPoint = "backgroundtask.js";
    
        //
        // Handle background task progress.
        //
        function ProgressHandler(task) {
            this.onProgress = function (args) {
                try {
                } catch (ex) {
    
                }
            };
        }
    
        //
        // Handle background task completion.
        //
        function CompleteHandler(task) {
            this.onCompleted = function (args) {
                try {
                    var key = task.taskId;
                    WinJS.Navigation.navigate("/frame/error.html");
                } catch (ex) {
    
                }
            };
        }
    
        function register() {
            try {
                var myTaskBuilder = new Windows.ApplicationModel.Background.BackgroundTaskBuilder();
                var myTrigger = new Windows.ApplicationModel.Background.TimeTrigger(15, false);
                myTaskBuilder.setTrigger(myTrigger);
                myTaskBuilder.taskEntryPoint = backgroundTaskEntryPoint;
                myTaskBuilder.name = backgroundTaskName;
                var myTask = myTaskBuilder.register();
                myTask.addEventListener("progress", new ProgressHandler(myTask).onProgress);
                myTask.addEventListener("completed", new CompleteHandler(myTask).onCompleted);
            }
            catch (e) {
                new Windows.UI.Popups.MessageDialog(e).showAsync().then(function () {
                    WinJS.Navigation.navigate("/frame/error.html");
                });
            }
        }
    
        function unRegister() {
            var iter = Windows.ApplicationModel.Background.BackgroundTaskRegistration.allTasks.first();
            var hascur = iter.hasCurrent;
            while (hascur) {
                var cur = iter.current.value;
                if (cur.name === backgroundTaskName) {
                    cur.unregister(true);
                }
                hascur = iter.moveNext();
            }
        }
    
        
        function initialize() {
            var bRegister = false;
            var iter = Windows.ApplicationModel.Background.BackgroundTaskRegistration.allTasks.first();
            var hascur = iter.hasCurrent;
            while (hascur) {
                var cur = iter.current.value;
                if (cur.name === backgroundTaskName) {
                    cur.addEventListener("progress", new ProgressHandler(cur).onProgress);
                    cur.addEventListener("completed", new CompleteHandler(cur).onCompleted);
                    bRegister = true;
                }
                hascur = iter.moveNext();
            }
    
            //if (!bRegister)
                register();
        }
    
        document.addEventListener("DOMContentLoaded", initialize, false);
    })();


    backgounrdtask.js

    (function () {
        "use strict";
    
        close();
    
    })();
    


    Sunday, March 18, 2012 2:59 PM

Answers

  • :(

    error: "document undefined."

    It's really strange that you get document undefined error. Does it work if you create a new project? Seem to me some serious problems occurred in your environment and breaks lots of things.. Did you test on a clean machine?

    Update: There is something wrong in my previous code. Try below please:

      var externalScript = document.createElement('script');
        externalScript.type = "text/javascript";
        externalScript.src = "/js/Weather.js";
        externalScript.onload = function () {
          //Code here
        }  
        document.getElementsByTagName("head")[0].appendChild(externalScript);


    Allen Chen [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.



    • Edited by Allen Chen - MSFT Wednesday, March 21, 2012 9:14 AM
    • Marked as answer by Allen-Hu Saturday, March 31, 2012 2:58 AM
    Wednesday, March 21, 2012 9:01 AM
  • Hi Xiao,

    See this thread for a list of samples and some further discussion:

    http://social.msdn.microsoft.com/Forums/en-US/winappswithhtml5/thread/3d2a4b8f-e6cc-4584-a595-0873aed6a11f

    -Jeff


    Jeff Sanders (MSFT)

    Thursday, March 22, 2012 12:13 PM
    Moderator

All replies

  • Hi,

    Is the application on the lock-screen? Please refer to Ben Hillis - MSFT's reply regarding this issue in the following doc:

    http://code.msdn.microsoft.com/windowsapps/Background-Task-Sample-9209ade9


    Allen Chen [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Monday, March 19, 2012 9:19 AM
  • Hi Allen,

    I try request lock-screen access, But app happened error "not found element."

        function requestLockScreenAccess() {
            var accessStatus = Windows.ApplicationModel.Background.BackgroundExecutionManager.requestAccessAsync();
            switch (accessStatus) {
                case Windows.ApplicationModel.Background.BackgroundAccessStatus.unspecified:
                    break;
            }
        }

    Where is need setting?

    Tuesday, March 20, 2012 7:22 AM
  • Hi Allen,

    I try request lock-screen access, But app happened error "not found element."

        function requestLockScreenAccess() {
            var accessStatus = Windows.ApplicationModel.Background.BackgroundExecutionManager.requestAccessAsync();
            switch (accessStatus) {
                case Windows.ApplicationModel.Background.BackgroundAccessStatus.unspecified:
                    break;
            }
        }

    Where is need setting?


    Hi,

    This API is async so you need to use .then(..) to get result and do further actions.

    For lock screen the latest SDK sample has "Lock screen apps sample". For background task you can refer to "Background task sample".

    You can get samples from:

    http://code.msdn.microsoft.com/windowsapps/Windows-8-Modern-Style-App-Samples


    Allen Chen [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Tuesday, March 20, 2012 7:59 AM
  • Hi Allen, thanks  for your reply.

    I use it also happened error "not found element."

        function requestLockScreenAccess() {
            Windows.ApplicationModel.Background.BackgroundExecutionManager.requestAccessAsync().then(function (accessStatus) {
                switch (accessStatus) {
                    case Windows.ApplicationModel.Background.BackgroundAccessStatus.unspecified:
                        break;
                }
            });
        }

    I run Background task by TimeTrigger event in "Background task Sample", "requestAccessAsync()" also happened error "not found element".

    Tuesday, March 20, 2012 8:10 AM
  • Hi,

    I'm unable to reproduce this issue. Are you using the public CP version?

    http://windows.microsoft.com/en-us/windows-8/download


    Allen Chen [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Tuesday, March 20, 2012 8:27 AM
  • Hi,

    Yes, my computer system is Windows 8 Consumer Preview 64bit.

    download it at http://windows.microsoft.com/en-us/windows-8/download.

    Windows.ApplicationModel.Background.BackgroundExecutionManager.requestAccessAsync()

    You system running this line script not happened error ?

    Tuesday, March 20, 2012 8:35 AM
  • Yes the sample in latest SDK works fine in my environment. It seems the difference is I'm using English 32 bit OS. Does it work for you if you try English 32 bit OS?

    Allen Chen [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Tuesday, March 20, 2012 9:04 AM
  • Hi, Allen.

    excuse me, an background task of JavaScript file how call external JavaScript file function?

    Wednesday, March 21, 2012 4:20 AM
  • Hi, Allen.

    excuse me, an background task of JavaScript file how call external JavaScript file function?

    I'm not quite understand what you want to do. If you want to call a JavaScript function that is defined in external file you can include that JavaScript file in the same page via script tag before calling it.

    And how about the original question? Does it work now?


    Allen Chen [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Wednesday, March 21, 2012 5:05 AM
  • I have a background task, it StartPage is a JavaScript file (backgroundtask.js), then I need to call another JavaScript file function.

    backgroundtask.js

    (function () {
    
        "use strict";
    
        var service = new Weather();
    
    })();

    Weather.js

    Weather() {
    
    }

    the background task trigger happens error "Weather Undefined."

    Because the backgroundtask.js can not be included in the Script tab of the page.

    Wednesday, March 21, 2012 5:39 AM
  • I have a background task, it StartPage is a JavaScript file (backgroundtask.js), then I need to call another JavaScript file function.

    backgroundtask.js

    (function () {
    
        "use strict";
    
        var service = new Weather();
    
    })();

    Weather.js

    Weather() {
    
    }

    the background task trigger happens error "Weather Undefined."

    Because the backgroundtask.js can not be included in the Script tab of the page.

    Hi,

    You can add the script element via JavaScript code. Add it before the script tag of the JavaScript code where you call this external JavaScript function would work. For instance:

         var externalScript = document.createElement('script');
        externalScript.src = "/js/Weather.js";
        document.head.childNodes[1].insertBefore(externalScript);


    Allen Chen [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.



    Wednesday, March 21, 2012 7:46 AM
  • :(

    error: "document undefined."

    Wednesday, March 21, 2012 8:47 AM
  • :(

    error: "document undefined."

    It's really strange that you get document undefined error. Does it work if you create a new project? Seem to me some serious problems occurred in your environment and breaks lots of things.. Did you test on a clean machine?

    Update: There is something wrong in my previous code. Try below please:

      var externalScript = document.createElement('script');
        externalScript.type = "text/javascript";
        externalScript.src = "/js/Weather.js";
        externalScript.onload = function () {
          //Code here
        }  
        document.getElementsByTagName("head")[0].appendChild(externalScript);


    Allen Chen [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.



    • Edited by Allen Chen - MSFT Wednesday, March 21, 2012 9:14 AM
    • Marked as answer by Allen-Hu Saturday, March 31, 2012 2:58 AM
    Wednesday, March 21, 2012 9:01 AM
  • I created a new project, but also happened error "document undefined".
    Please see my code source.

    service.js

    (function () {
    
        var backgroundTaskName = "ExternalScriptBackgroundTask";
        var backgroundTaskEntryPoint = "script.js";
    
    
        //
        // Handle background task progress.
        //
        function ProgressHandler(task) {
            this.onProgress = function (args) {
                try {
                } catch (ex) {
    
                }
            };
        }
    
        //
        // Handle background task completion.
        //
        function CompleteHandler(task) {
            this.onCompleted = function (args) {
                try {
                    var key = task.taskId;
    
                } catch (ex) {
    
                }
            };
        }
    
    
        function register() {
            try {
                var myTaskBuilder = new Windows.ApplicationModel.Background.BackgroundTaskBuilder();
                var myTrigger = new Windows.ApplicationModel.Background.SystemTrigger(Windows.ApplicationModel.Background.SystemTriggerType.timeZoneChange, false);
                myTaskBuilder.setTrigger(myTrigger);
                myTaskBuilder.taskEntryPoint = backgroundTaskEntryPoint;
                myTaskBuilder.name = backgroundTaskName;
                var myTask = myTaskBuilder.register();
                myTask.addEventListener("progress", new ProgressHandler(myTask).onProgress);
                myTask.addEventListener("completed", new CompleteHandler(myTask).onCompleted);
            }
            catch (e) {
                new Windows.UI.Popups.MessageDialog(e).showAsync().then(function () {
                    WinJS.Navigation.navigate("/frame/error.html");
                });
            }
        }
    
        function unRegister() {
            var iter = Windows.ApplicationModel.Background.BackgroundTaskRegistration.allTasks.first();
            var hascur = iter.hasCurrent;
            while (hascur) {
                var cur = iter.current.value;
                if (cur.name === backgroundTaskName) {
                    cur.unregister(true);
                }
                hascur = iter.moveNext();
            }
        }
    
        function initialize() {
            unRegister();
            var bRegister = false;
            var iter = Windows.ApplicationModel.Background.BackgroundTaskRegistration.allTasks.first();
            var hascur = iter.hasCurrent;
            while (hascur) {
                var cur = iter.current.value;
                if (cur.name === backgroundTaskName) {
                    cur.addEventListener("progress", new ProgressHandler(cur).onProgress);
                    cur.addEventListener("completed", new CompleteHandler(cur).onCompleted);
                    bRegister = true;
                }
                hascur = iter.moveNext();
            }
            if (!bRegister)
                register();
        }
    
        document.addEventListener("DOMContentLoaded", initialize, false);
    
    })();

    script.js

    (function () {
    
        "use strict";
    
        var externalScript = document.createElement('script');
        externalScript.type = "text/javascript";
        externalScript.src = "/js/Weather.js";
        externalScript.onload = function () {
            //Code here
        }
        document.getElementsByTagName("head")[0].appendChild(externalScript);
    
    })();

    /js/Weather.js

    (function () {
    
    })();

    default.html

    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <meta charset="utf-8">
        <title>ExternalScript</title>
    
        <!-- WinJS references -->
        <link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet">
        <script src="//Microsoft.WinJS.0.6/js/base.js"></script>
        <script src="//Microsoft.WinJS.0.6/js/ui.js"></script>
    
        <!-- ExternalScript references -->
        <link href="/css/default.css" rel="stylesheet">
        <script src="/js/default.js"></script>
        <script src="service.js"></script>
    </head>
    <body>
        <p>Content goes here</p>
    </body>
    </html>
    

    happened error:

    Can you speak Chinese? Or do you have some colleagues is Chinese?

    Wednesday, March 21, 2012 1:50 PM
  • There is no 'document' object for a background task script so you cannot use that method.

    You can copy and paste the script into your background task JS or you can read the js file in and eval it.

    For more information see this post:

    http://social.msdn.microsoft.com/Forums/sr-Latn-CS/winappswithhtml5/thread/54d6d2d4-a727-44fa-98f9-3339d7ab88b8

    -Jeff


    Jeff Sanders (MSFT)

    Wednesday, March 21, 2012 7:02 PM
    Moderator
  • Hi, Jeff.

    thanks for your reply.

    I need use WinJS.xhr() in background task script, How to do it?

    Please help me write an example of you.

    Thursday, March 22, 2012 1:20 AM
  • Hi Xiao,

    See this thread for a list of samples and some further discussion:

    http://social.msdn.microsoft.com/Forums/en-US/winappswithhtml5/thread/3d2a4b8f-e6cc-4584-a595-0873aed6a11f

    -Jeff


    Jeff Sanders (MSFT)

    Thursday, March 22, 2012 12:13 PM
    Moderator
  • Hi Jeff,

    The above problems have been resolved, but I have a problem.Why time-triggeredbackground task sometimes starts and sometimes could not be activated?I can confirmthat it has access to the lock screen, and successfully registered.The background task isrunning on what process?

    Thursday, March 22, 2012 2:56 PM
  • Using importScript include base.js
    Monday, November 11, 2013 9:28 AM