Search code examples
androidiosiphonetitaniumtitanium-mobile

Create thread in Titanium


I need to create a thread in titanium to due some work in background. I have searched around in google and found this:

var queue = Ti.Async.createQueue();

var job = queue.dispatch(function() {

});

But now i don't now how to keep the thread alive (if this is a thread) after the first execution and how due I set the delay for each execution?


Solution

  • I personally use another method to create "background processes" in titanium.

    I create a javascript file containing the elements i need to run in background, and apply a "setInterval" to it (to make it run endlessly), like this:

    //FILENAME: bgTask.js
    
    function myFunc() {
        //Code here
    }
    
    setInterval(myFunc, <time in milliseconds>);
    

    Now, i create the controller without view to get it running. For instance, if i need it to run in background in the entire app, i run an "Alloy.createController" in "index.js", but never get the view or show it. This creates and executes the controller in the background.

    In "index.js" i use

    Alloy.createController("bgTask");
    

    to create the background process.


    In case you want to have the background process only run a single time (or a definite number of times) you can change the background process file (bgTask.js in this case) to follow your needs, and create the controller every time you need to run the task.


    To get the result from the background process, you can use global variables or any other method you see fit. To use global variables, use

    Ti.App.<varname> = <something>
    

    This way the value gets saved for the entire application. Works for iOS, Android and Windows Phone.

    Sorry for the late answer, hope this helped.