Upgrade to ExtJS 4.0.0 - Released 04/26/2011
[extjs.git] / src / core / src / util / TaskManager.js
1 /**
2  * @class Ext.util.TaskRunner
3  * Provides the ability to execute one or more arbitrary tasks in a multithreaded
4  * manner.  Generally, you can use the singleton {@link Ext.TaskManager} instead, but
5  * if needed, you can create separate instances of TaskRunner.  Any number of
6  * separate tasks can be started at any time and will run independently of each
7  * other. Example usage:
8  * <pre><code>
9 // Start a simple clock task that updates a div once per second
10 var updateClock = function(){
11     Ext.fly('clock').update(new Date().format('g:i:s A'));
12
13 var task = {
14     run: updateClock,
15     interval: 1000 //1 second
16 }
17 var runner = new Ext.util.TaskRunner();
18 runner.start(task);
19
20 // equivalent using TaskManager
21 Ext.TaskManager.start({
22     run: updateClock,
23     interval: 1000
24 });
25
26  * </code></pre>
27  * <p>See the {@link #start} method for details about how to configure a task object.</p>
28  * Also see {@link Ext.util.DelayedTask}. 
29  * 
30  * @constructor
31  * @param {Number} interval (optional) The minimum precision in milliseconds supported by this TaskRunner instance
32  * (defaults to 10)
33  */
34 Ext.ns('Ext.util');
35
36 Ext.util.TaskRunner = function(interval) {
37     interval = interval || 10;
38     var tasks = [],
39     removeQueue = [],
40     id = 0,
41     running = false,
42
43     // private
44     stopThread = function() {
45         running = false;
46         clearInterval(id);
47         id = 0;
48     },
49
50     // private
51     startThread = function() {
52         if (!running) {
53             running = true;
54             id = setInterval(runTasks, interval);
55         }
56     },
57
58     // private
59     removeTask = function(t) {
60         removeQueue.push(t);
61         if (t.onStop) {
62             t.onStop.apply(t.scope || t);
63         }
64     },
65
66     // private
67     runTasks = function() {
68         var rqLen = removeQueue.length,
69             now = new Date().getTime(),
70             i;
71
72         if (rqLen > 0) {
73             for (i = 0; i < rqLen; i++) {
74                 Ext.Array.remove(tasks, removeQueue[i]);
75             }
76             removeQueue = [];
77             if (tasks.length < 1) {
78                 stopThread();
79                 return;
80             }
81         }
82         i = 0;
83         var t,
84             itime,
85             rt,
86             len = tasks.length;
87         for (; i < len; ++i) {
88             t = tasks[i];
89             itime = now - t.taskRunTime;
90             if (t.interval <= itime) {
91                 rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]);
92                 t.taskRunTime = now;
93                 if (rt === false || t.taskRunCount === t.repeat) {
94                     removeTask(t);
95                     return;
96                 }
97             }
98             if (t.duration && t.duration <= (now - t.taskStartTime)) {
99                 removeTask(t);
100             }
101         }
102     };
103
104     /**
105      * Starts a new task.
106      * @method start
107      * @param {Object} task <p>A config object that supports the following properties:<ul>
108      * <li><code>run</code> : Function<div class="sub-desc"><p>The function to execute each time the task is invoked. The
109      * function will be called at each interval and passed the <code>args</code> argument if specified, and the
110      * current invocation count if not.</p>
111      * <p>If a particular scope (<code>this</code> reference) is required, be sure to specify it using the <code>scope</code> argument.</p>
112      * <p>Return <code>false</code> from this function to terminate the task.</p></div></li>
113      * <li><code>interval</code> : Number<div class="sub-desc">The frequency in milliseconds with which the task
114      * should be invoked.</div></li>
115      * <li><code>args</code> : Array<div class="sub-desc">(optional) An array of arguments to be passed to the function
116      * specified by <code>run</code>. If not specified, the current invocation count is passed.</div></li>
117      * <li><code>scope</code> : Object<div class="sub-desc">(optional) The scope (<tt>this</tt> reference) in which to execute the
118      * <code>run</code> function. Defaults to the task config object.</div></li>
119      * <li><code>duration</code> : Number<div class="sub-desc">(optional) The length of time in milliseconds to invoke
120      * the task before stopping automatically (defaults to indefinite).</div></li>
121      * <li><code>repeat</code> : Number<div class="sub-desc">(optional) The number of times to invoke the task before
122      * stopping automatically (defaults to indefinite).</div></li>
123      * </ul></p>
124      * <p>Before each invocation, Ext injects the property <code>taskRunCount</code> into the task object so
125      * that calculations based on the repeat count can be performed.</p>
126      * @return {Object} The task
127      */
128     this.start = function(task) {
129         tasks.push(task);
130         task.taskStartTime = new Date().getTime();
131         task.taskRunTime = 0;
132         task.taskRunCount = 0;
133         startThread();
134         return task;
135     };
136
137     /**
138      * Stops an existing running task.
139      * @method stop
140      * @param {Object} task The task to stop
141      * @return {Object} The task
142      */
143     this.stop = function(task) {
144         removeTask(task);
145         return task;
146     };
147
148     /**
149      * Stops all tasks that are currently running.
150      * @method stopAll
151      */
152     this.stopAll = function() {
153         stopThread();
154         for (var i = 0, len = tasks.length; i < len; i++) {
155             if (tasks[i].onStop) {
156                 tasks[i].onStop();
157             }
158         }
159         tasks = [];
160         removeQueue = [];
161     };
162 };
163
164 /**
165  * @class Ext.TaskManager
166  * @extends Ext.util.TaskRunner
167  * A static {@link Ext.util.TaskRunner} instance that can be used to start and stop arbitrary tasks.  See
168  * {@link Ext.util.TaskRunner} for supported methods and task config properties.
169  * <pre><code>
170 // Start a simple clock task that updates a div once per second
171 var task = {
172     run: function(){
173         Ext.fly('clock').update(new Date().format('g:i:s A'));
174     },
175     interval: 1000 //1 second
176 }
177 Ext.TaskManager.start(task);
178 </code></pre>
179  * <p>See the {@link #start} method for details about how to configure a task object.</p>
180  * @singleton
181  */
182 Ext.TaskManager = Ext.create('Ext.util.TaskRunner');