1 /* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
2 /* vim: set ts=2 et sw=2 tw=80 filetype=javascript: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
10 * Sets up a function or an asynchronous task whose execution can be triggered
11 * after a defined delay. Multiple attempts to run the task before the delay
12 * has passed are coalesced. The task cannot be re-entered while running, but
13 * can be executed again after a previous run finished.
15 * A common use case occurs when a data structure should be saved into a file
16 * every time the data changes, using asynchronous calls, and multiple changes
17 * to the data may happen within a short time:
19 * let saveDeferredTask = new DeferredTask(async function() {
20 * await OS.File.writeAtomic(...);
21 * // Any uncaught exception will be reported.
24 * // The task is ready, but will not be executed until requested.
26 * The "arm" method can be used to start the internal timer that will result in
27 * the eventual execution of the task. Multiple attempts to arm the timer don't
28 * introduce further delays:
30 * saveDeferredTask.arm();
32 * // The task will be executed in 2 seconds from now.
34 * await waitOneSecond();
35 * saveDeferredTask.arm();
37 * // The task will be executed in 1 second from now.
39 * The timer can be disarmed to reset the delay, or just to cancel execution:
41 * saveDeferredTask.disarm();
42 * saveDeferredTask.arm();
44 * // The task will be executed in 2 seconds from now.
46 * When the internal timer fires and the execution of the task starts, the task
47 * cannot be canceled anymore. It is however possible to arm the timer again
48 * during the execution of the task, in which case the task will need to finish
49 * before the timer is started again, thus guaranteeing a time of inactivity
50 * between executions that is at least equal to the provided delay.
52 * The "finalize" method can be used to ensure that the task terminates
53 * properly. The promise it returns is resolved only after the last execution
54 * of the task is finished. To guarantee that the task is executed for the
55 * last time, the method prevents any attempt to arm the timer again.
57 * If the timer is already armed when the "finalize" method is called, then the
58 * task is executed immediately. If the task was already running at this point,
59 * then one last execution from start to finish will happen again, immediately
60 * after the current execution terminates. If the timer is not armed, the
61 * "finalize" method only ensures that any running task terminates.
63 * For example, during shutdown, you may want to ensure that any pending write
64 * is processed, using the latest version of the data if the timer is armed:
66 * AsyncShutdown.profileBeforeChange.addBlocker(
67 * "Example service: shutting down",
68 * () => saveDeferredTask.finalize()
71 * Instead, if you are going to delete the saved data from disk anyways, you
72 * might as well prevent any pending write from starting, while still ensuring
73 * that any write that is currently in progress terminates, so that the file is
76 * saveDeferredTask.disarm();
77 * saveDeferredTask.finalize().then(() => OS.File.remove(...))
78 * .then(null, Components.utils.reportError);
83 ChromeUtils.defineESModuleGetters(lazy, {
84 PromiseUtils: "resource://gre/modules/PromiseUtils.sys.mjs",
87 const Timer = Components.Constructor(
88 "@mozilla.org/timer;1",
96 * Sets up a task whose execution can be triggered after a delay.
99 * Function to execute. If the function returns a promise, the task is
100 * not considered complete until that promise resolves. This
101 * task is never re-entered while running.
103 * Time between executions, in milliseconds. Multiple attempts to run
104 * the task before the delay has passed are coalesced. This time of
105 * inactivity is guaranteed to pass between multiple executions of the
106 * task, except on finalization, when the task may restart immediately
107 * after the previous execution finished.
108 * @param aIdleTimeoutMs
109 * The maximum time to wait for an idle slot on the main thread after
110 * aDelayMs have elapsed. If omitted, waits indefinitely for an idle
113 export var DeferredTask = function (aTaskFn, aDelayMs, aIdleTimeoutMs) {
114 this._taskFn = aTaskFn;
115 this._delayMs = aDelayMs;
116 this._timeoutMs = aIdleTimeoutMs;
117 this._caller = new Error().stack.split("\n", 2)[1];
118 let markerString = `delay: ${aDelayMs}ms`;
119 if (aIdleTimeoutMs) {
120 markerString += `, idle timeout: ${aIdleTimeoutMs}`;
122 ChromeUtils.addProfilerMarker(
124 { captureStack: true },
129 DeferredTask.prototype = {
131 * Function to execute.
136 * Time between executions, in milliseconds.
141 * Indicates whether the task is currently requested to start again later,
142 * regardless of whether it is currently running.
150 * Indicates whether the task is currently running. This is always true when
151 * read from code inside the task function, but can also be true when read
152 * from external code, in case the task is an asynchronous function.
155 return !!this._runningPromise;
159 * Promise resolved when the current execution of the task terminates, or null
160 * if the task is not currently running.
162 _runningPromise: null,
165 * nsITimer used for triggering the task after a delay, or null in case the
166 * task is running or there is no task scheduled for execution.
171 * Actually starts the timer with the delay specified on construction.
175 if (this._timeoutMs === 0) {
176 callback = () => this._timerCallback();
179 this._startIdleDispatch(() => {
180 // _timer could have changed by now:
181 // - to null if disarm() or finalize() has been called.
182 // - to a new nsITimer if disarm() was called, followed by arm().
183 // In either case, don't invoke _timerCallback any more.
184 if (this._timer === timer) {
185 this._timerCallback();
190 timer = new Timer(callback, this._delayMs, Ci.nsITimer.TYPE_ONE_SHOT);
195 * Dispatches idle task. Can be overridden for testing by test_DeferredTask.
197 _startIdleDispatch(callback, timeout) {
198 ChromeUtils.idleDispatch(callback, { timeout });
202 * Requests the execution of the task after the delay specified on
203 * construction. Multiple calls don't introduce further delays. If the task
204 * is running, the delay will start when the current execution finishes.
206 * The task will always be executed on a different tick of the event loop,
207 * even if the delay specified on construction is zero. Multiple "arm" calls
208 * within the same tick of the event loop are guaranteed to result in a single
209 * execution of the task.
211 * @note By design, this method doesn't provide a way for the caller to detect
212 * when the next execution terminates, or collect a result. In fact,
213 * doing that would often result in duplicate processing or logging. If
214 * a special operation or error logging is needed on completion, it can
215 * be better handled from within the task itself, for example using a
216 * try/catch/finally clause in the task. The "finalize" method can be
217 * used in the common case of waiting for completion on shutdown.
220 if (this._finalized) {
221 throw new Error("Unable to arm timer, the object has been finalized.");
226 // In case the timer callback is running, do not create the timer now,
227 // because this will be handled by the timer callback itself. Also, the
228 // timer is not restarted in case it is already running.
229 if (!this._runningPromise && !this._timer) {
235 * Cancels any request for a delayed the execution of the task, though the
236 * task itself cannot be canceled in case it is already running.
238 * This method stops any currently running timer, thus the delay will restart
239 * from its original value in case the "arm" method is called again.
244 // Calling the "cancel" method and discarding the timer reference makes
245 // sure that the timer callback will not be called later, even if the
246 // timer thread has already posted the timer event on the main thread.
247 this._timer.cancel();
253 * Ensures that any pending task is executed from start to finish, while
254 * preventing any attempt to arm the timer again.
256 * - If the task is running and the timer is armed, then one last execution
257 * from start to finish will happen again, immediately after the current
258 * execution terminates, then the returned promise will be resolved.
259 * - If the task is running and the timer is not armed, the returned promise
260 * will be resolved when the current execution terminates.
261 * - If the task is not running and the timer is armed, then the task is
262 * started immediately, and the returned promise resolves when the new
263 * execution terminates.
264 * - If the task is not running and the timer is not armed, the method returns
265 * a resolved promise.
268 * @resolves After the last execution of the task is finished.
272 if (this._finalized) {
273 throw new Error("The object has been already finalized.");
275 this._finalized = true;
277 // If the timer is armed, it means that the task is not running but it is
278 // scheduled for execution. Cancel the timer and run the task immediately,
279 // so we don't risk blocking async shutdown longer than necessary.
282 this._timerCallback();
285 // Wait for the operation to be completed, or resolve immediately.
286 if (this._runningPromise) {
287 return this._runningPromise;
289 return Promise.resolve();
294 * Whether the DeferredTask has been finalized, and it cannot be armed anymore.
297 return this._finalized;
301 * Timer callback used to run the delayed task.
304 let runningDeferred = lazy.PromiseUtils.defer();
306 // All these state changes must occur at the same time directly inside the
307 // timer callback, to prevent race conditions and to ensure that all the
308 // methods behave consistently even if called from inside the task. This
309 // means that the assignment of "this._runningPromise" must complete before
310 // the task gets a chance to start.
313 this._runningPromise = runningDeferred.promise;
315 runningDeferred.resolve(
317 // Execute the provided function asynchronously.
318 await this._runTask();
320 // Now that the task has finished, we check the state of the object to
321 // determine if we should restart the task again.
323 if (!this._finalized) {
326 // Execute the task again immediately, for the last time. The isArmed
327 // property should return false while the task is running, and should
328 // remain false after the last execution terminates.
330 await this._runTask();
334 // Indicate that the execution of the task has finished. This happens
335 // synchronously with the previous state changes in the function.
336 this._runningPromise = null;
337 })().catch(console.error)
342 * Executes the associated task and catches exceptions.
345 let startTime = Cu.now();
347 await this._taskFn();
351 ChromeUtils.addProfilerMarker(