Merge from emacs-24; up to 2012-05-08T14:11:47Z!monnier@iro.umontreal.ca
[emacs.git] / lisp / emacs-lisp / timer.el
blob284c591fc6193106d7a3070d93390d37814f8929
1 ;;; timer.el --- run a function with args at some time in future
3 ;; Copyright (C) 1996, 2001-2012 Free Software Foundation, Inc.
5 ;; Maintainer: FSF
6 ;; Package: emacs
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; This package gives you the capability to run Emacs Lisp commands at
26 ;; specified times in the future, either as one-shots or periodically.
28 ;;; Code:
30 ;; Layout of a timer vector:
31 ;; [triggered-p high-seconds low-seconds usecs repeat-delay
32 ;; function args idle-delay psecs]
33 ;; triggered-p is nil if the timer is active (waiting to be triggered),
34 ;; t if it is inactive ("already triggered", in theory)
36 (eval-when-compile (require 'cl-lib))
38 (cl-defstruct (timer
39 (:constructor nil)
40 (:copier nil)
41 (:constructor timer-create ())
42 (:type vector)
43 (:conc-name timer--))
44 (triggered t)
45 high-seconds low-seconds usecs repeat-delay function args idle-delay psecs)
47 (defun timerp (object)
48 "Return t if OBJECT is a timer."
49 (and (vectorp object) (= (length object) 9)))
51 ;; Pseudo field `time'.
52 (defun timer--time (timer)
53 (list (timer--high-seconds timer)
54 (timer--low-seconds timer)
55 (timer--usecs timer)
56 (timer--psecs timer)))
58 (gv-define-simple-setter timer--time
59 (lambda (timer time)
60 (or (timerp timer) (error "Invalid timer"))
61 (setf (timer--high-seconds timer) (pop time))
62 (let ((low time) (usecs 0) (psecs 0))
63 (if (consp time)
64 (progn
65 (setq low (pop time))
66 (if time
67 (progn
68 (setq usecs (pop time))
69 (if time
70 (setq psecs (car time)))))))
71 (setf (timer--low-seconds timer) low)
72 (setf (timer--usecs timer) usecs)
73 (setf (timer--psecs timer) psecs))))
76 (defun timer-set-time (timer time &optional delta)
77 "Set the trigger time of TIMER to TIME.
78 TIME must be in the internal format returned by, e.g., `current-time'.
79 If optional third argument DELTA is a positive number, make the timer
80 fire repeatedly that many seconds apart."
81 (setf (timer--time timer) time)
82 (setf (timer--repeat-delay timer) (and (numberp delta) (> delta 0) delta))
83 timer)
85 (defun timer-set-idle-time (timer secs &optional repeat)
86 "Set the trigger idle time of TIMER to SECS.
87 SECS may be an integer, floating point number, or the internal
88 time format returned by, e.g., `current-idle-time'.
89 If optional third argument REPEAT is non-nil, make the timer
90 fire each time Emacs is idle for that many seconds."
91 (if (consp secs)
92 (setf (timer--time timer) secs)
93 (setf (timer--time timer) '(0 0 0))
94 (timer-inc-time timer secs))
95 (setf (timer--repeat-delay timer) repeat)
96 timer)
98 (defun timer-next-integral-multiple-of-time (time secs)
99 "Yield the next value after TIME that is an integral multiple of SECS.
100 More precisely, the next value, after TIME, that is an integral multiple
101 of SECS seconds since the epoch. SECS may be a fraction."
102 (let* ((trillion 1e12)
103 (time-sec (+ (nth 1 time)
104 (* 65536.0 (nth 0 time))))
105 (delta-sec (mod (- time-sec) secs))
106 (next-sec (+ time-sec (ffloor delta-sec)))
107 (next-sec-psec (ffloor (* trillion (mod delta-sec 1))))
108 (sub-time-psec (+ (or (nth 3 time) 0)
109 (* 1e6 (nth 2 time))))
110 (psec-diff (- sub-time-psec next-sec-psec)))
111 (if (and (<= next-sec time-sec) (< 0 psec-diff))
112 (setq next-sec-psec (+ sub-time-psec
113 (mod (- psec-diff) (* trillion secs)))))
114 (setq next-sec (+ next-sec (floor next-sec-psec trillion)))
115 (setq next-sec-psec (mod next-sec-psec trillion))
116 (list (floor next-sec 65536)
117 (floor (mod next-sec 65536))
118 (floor next-sec-psec 1000000)
119 (floor (mod next-sec-psec 1000000)))))
121 (defun timer-relative-time (time secs &optional usecs psecs)
122 "Advance TIME by SECS seconds and optionally USECS nanoseconds
123 and PSECS picoseconds. SECS may be either an integer or a
124 floating point number."
125 (let ((delta (if (floatp secs)
126 (seconds-to-time secs)
127 (list (floor secs 65536) (mod secs 65536)))))
128 (if (or usecs psecs)
129 (setq delta (time-add delta (list 0 0 (or usecs 0) (or psecs 0)))))
130 (time-add time delta)))
132 (defun timer--time-less-p (t1 t2)
133 "Say whether time value T1 is less than time value T2."
134 (time-less-p (timer--time t1) (timer--time t2)))
136 (defun timer-inc-time (timer secs &optional usecs psecs)
137 "Increment the time set in TIMER by SECS seconds, USECS nanoseconds,
138 and PSECS picoseconds. SECS may be a fraction. If USECS or PSECS are
139 omitted, they are treated as zero."
140 (setf (timer--time timer)
141 (timer-relative-time (timer--time timer) secs usecs psecs)))
143 (defun timer-set-time-with-usecs (timer time usecs &optional delta)
144 "Set the trigger time of TIMER to TIME plus USECS.
145 TIME must be in the internal format returned by, e.g., `current-time'.
146 The microsecond count from TIME is ignored, and USECS is used instead.
147 If optional fourth argument DELTA is a positive number, make the timer
148 fire repeatedly that many seconds apart."
149 (declare (obsolete "use `timer-set-time' and `timer-inc-time' instead."
150 "22.1"))
151 (setf (timer--time timer) time)
152 (setf (timer--usecs timer) usecs)
153 (setf (timer--psecs timer) 0)
154 (setf (timer--repeat-delay timer) (and (numberp delta) (> delta 0) delta))
155 timer)
157 (defun timer-set-function (timer function &optional args)
158 "Make TIMER call FUNCTION with optional ARGS when triggering."
159 (or (timerp timer)
160 (error "Invalid timer"))
161 (setf (timer--function timer) function)
162 (setf (timer--args timer) args)
163 timer)
165 (defun timer--activate (timer &optional triggered-p reuse-cell idle)
166 (if (and (timerp timer)
167 (integerp (timer--high-seconds timer))
168 (integerp (timer--low-seconds timer))
169 (integerp (timer--usecs timer))
170 (integerp (timer--psecs timer))
171 (timer--function timer))
172 (let ((timers (if idle timer-idle-list timer-list))
173 last)
174 ;; Skip all timers to trigger before the new one.
175 (while (and timers (timer--time-less-p (car timers) timer))
176 (setq last timers
177 timers (cdr timers)))
178 (if reuse-cell
179 (progn
180 (setcar reuse-cell timer)
181 (setcdr reuse-cell timers))
182 (setq reuse-cell (cons timer timers)))
183 ;; Insert new timer after last which possibly means in front of queue.
184 (cond (last (setcdr last reuse-cell))
185 (idle (setq timer-idle-list reuse-cell))
186 (t (setq timer-list reuse-cell)))
187 (setf (timer--triggered timer) triggered-p)
188 (setf (timer--idle-delay timer) idle)
189 nil)
190 (error "Invalid or uninitialized timer")))
192 (defun timer-activate (timer &optional triggered-p reuse-cell)
193 "Insert TIMER into `timer-list'.
194 If TRIGGERED-P is t, make TIMER inactive (put it on the list, but
195 mark it as already triggered). To remove it, use `cancel-timer'.
197 REUSE-CELL, if non-nil, is a cons cell to reuse when inserting
198 TIMER into `timer-list' (usually a cell removed from that list by
199 `cancel-timer-internal'; using this reduces consing for repeat
200 timers). If nil, allocate a new cell."
201 (timer--activate timer triggered-p reuse-cell nil))
203 (defun timer-activate-when-idle (timer &optional dont-wait reuse-cell)
204 "Insert TIMER into `timer-idle-list'.
205 This arranges to activate TIMER whenever Emacs is next idle.
206 If optional argument DONT-WAIT is non-nil, set TIMER to activate
207 immediately \(see below\), or at the right time, if Emacs is
208 already idle.
210 REUSE-CELL, if non-nil, is a cons cell to reuse when inserting
211 TIMER into `timer-idle-list' (usually a cell removed from that
212 list by `cancel-timer-internal'; using this reduces consing for
213 repeat timers). If nil, allocate a new cell.
215 Using non-nil DONT-WAIT is not recommended when activating an
216 idle timer from an idle timer handler, if the timer being
217 activated has an idleness time that is smaller or equal to
218 the time of the current timer. That's because the activated
219 timer will fire right away."
220 (timer--activate timer (not dont-wait) reuse-cell 'idle))
222 (defalias 'disable-timeout 'cancel-timer)
224 (defun cancel-timer (timer)
225 "Remove TIMER from the list of active timers."
226 (or (timerp timer)
227 (error "Invalid timer"))
228 (setq timer-list (delq timer timer-list))
229 (setq timer-idle-list (delq timer timer-idle-list))
230 nil)
232 (defun cancel-timer-internal (timer)
233 "Remove TIMER from the list of active timers or idle timers.
234 Only to be used in this file. It returns the cons cell
235 that was removed from the timer list."
236 (let ((cell1 (memq timer timer-list))
237 (cell2 (memq timer timer-idle-list)))
238 (if cell1
239 (setq timer-list (delq timer timer-list)))
240 (if cell2
241 (setq timer-idle-list (delq timer timer-idle-list)))
242 (or cell1 cell2)))
244 (defun cancel-function-timers (function)
245 "Cancel all timers which would run FUNCTION.
246 This affects ordinary timers such as are scheduled by `run-at-time',
247 and idle timers such as are scheduled by `run-with-idle-timer'."
248 (interactive "aCancel timers of function: ")
249 (dolist (timer timer-list)
250 (if (eq (timer--function timer) function)
251 (setq timer-list (delq timer timer-list))))
252 (dolist (timer timer-idle-list)
253 (if (eq (timer--function timer) function)
254 (setq timer-idle-list (delq timer timer-idle-list)))))
256 ;; Record the last few events, for debugging.
257 (defvar timer-event-last nil
258 "Last timer that was run.")
259 (defvar timer-event-last-1 nil
260 "Next-to-last timer that was run.")
261 (defvar timer-event-last-2 nil
262 "Third-to-last timer that was run.")
264 (defcustom timer-max-repeats 10
265 "Maximum number of times to repeat a timer, if many repeats are delayed.
266 Timer invocations can be delayed because Emacs is suspended or busy,
267 or because the system's time changes. If such an occurrence makes it
268 appear that many invocations are overdue, this variable controls
269 how many will really happen."
270 :type 'integer
271 :group 'internal)
273 (defun timer-until (timer time)
274 "Calculate number of seconds from when TIMER will run, until TIME.
275 TIMER is a timer, and stands for the time when its next repeat is scheduled.
276 TIME is a time-list."
277 (- (float-time time) (float-time (timer--time timer))))
279 (defun timer-event-handler (timer)
280 "Call the handler for the timer TIMER.
281 This function is called, by name, directly by the C code."
282 (setq timer-event-last-2 timer-event-last-1)
283 (setq timer-event-last-1 timer-event-last)
284 (setq timer-event-last timer)
285 (let ((inhibit-quit t))
286 (if (timerp timer)
287 (let (retrigger cell)
288 ;; Delete from queue. Record the cons cell that was used.
289 (setq cell (cancel-timer-internal timer))
290 ;; Re-schedule if requested.
291 (if (timer--repeat-delay timer)
292 (if (timer--idle-delay timer)
293 (timer-activate-when-idle timer nil cell)
294 (timer-inc-time timer (timer--repeat-delay timer) 0)
295 ;; If real time has jumped forward,
296 ;; perhaps because Emacs was suspended for a long time,
297 ;; limit how many times things get repeated.
298 (if (and (numberp timer-max-repeats)
299 (< 0 (timer-until timer (current-time))))
300 (let ((repeats (/ (timer-until timer (current-time))
301 (timer--repeat-delay timer))))
302 (if (> repeats timer-max-repeats)
303 (timer-inc-time timer (* (timer--repeat-delay timer)
304 repeats)))))
305 (timer-activate timer t cell)
306 (setq retrigger t)))
307 ;; Run handler.
308 ;; We do this after rescheduling so that the handler function
309 ;; can cancel its own timer successfully with cancel-timer.
310 (condition-case nil
311 ;; Timer functions should not change the current buffer.
312 ;; If they do, all kinds of nasty surprises can happen,
313 ;; and it can be hellish to track down their source.
314 (save-current-buffer
315 (apply (timer--function timer) (timer--args timer)))
316 (error nil))
317 (if retrigger
318 (setf (timer--triggered timer) nil)))
319 (error "Bogus timer event"))))
321 ;; This function is incompatible with the one in levents.el.
322 (defun timeout-event-p (event)
323 "Non-nil if EVENT is a timeout event."
324 (and (listp event) (eq (car event) 'timer-event)))
327 (declare-function diary-entry-time "diary-lib" (s))
329 (defun run-at-time (time repeat function &rest args)
330 "Perform an action at time TIME.
331 Repeat the action every REPEAT seconds, if REPEAT is non-nil.
332 TIME should be one of: a string giving an absolute time like
333 \"11:23pm\" (the acceptable formats are those recognized by
334 `diary-entry-time'; note that such times are interpreted as times
335 today, even if in the past); a string giving a relative time like
336 \"2 hours 35 minutes\" (the acceptable formats are those
337 recognized by `timer-duration'); nil meaning now; a number of
338 seconds from now; a value from `encode-time'; or t (with non-nil
339 REPEAT) meaning the next integral multiple of REPEAT. REPEAT may
340 be an integer or floating point number. The action is to call
341 FUNCTION with arguments ARGS.
343 This function returns a timer object which you can use in `cancel-timer'."
344 (interactive "sRun at time: \nNRepeat interval: \naFunction: ")
346 (or (null repeat)
347 (and (numberp repeat) (< 0 repeat))
348 (error "Invalid repetition interval"))
350 ;; Special case: nil means "now" and is useful when repeating.
351 (if (null time)
352 (setq time (current-time)))
354 ;; Special case: t means the next integral multiple of REPEAT.
355 (if (and (eq time t) repeat)
356 (setq time (timer-next-integral-multiple-of-time (current-time) repeat)))
358 ;; Handle numbers as relative times in seconds.
359 (if (numberp time)
360 (setq time (timer-relative-time (current-time) time)))
362 ;; Handle relative times like "2 hours 35 minutes"
363 (if (stringp time)
364 (let ((secs (timer-duration time)))
365 (if secs
366 (setq time (timer-relative-time (current-time) secs)))))
368 ;; Handle "11:23pm" and the like. Interpret it as meaning today
369 ;; which admittedly is rather stupid if we have passed that time
370 ;; already. (Though only Emacs hackers hack Emacs at that time.)
371 (if (stringp time)
372 (progn
373 (require 'diary-lib)
374 (let ((hhmm (diary-entry-time time))
375 (now (decode-time)))
376 (if (>= hhmm 0)
377 (setq time
378 (encode-time 0 (% hhmm 100) (/ hhmm 100) (nth 3 now)
379 (nth 4 now) (nth 5 now) (nth 8 now)))))))
381 (or (consp time)
382 (error "Invalid time format"))
384 (let ((timer (timer-create)))
385 (timer-set-time timer time repeat)
386 (timer-set-function timer function args)
387 (timer-activate timer)
388 timer))
390 (defun run-with-timer (secs repeat function &rest args)
391 "Perform an action after a delay of SECS seconds.
392 Repeat the action every REPEAT seconds, if REPEAT is non-nil.
393 SECS and REPEAT may be integers or floating point numbers.
394 The action is to call FUNCTION with arguments ARGS.
396 This function returns a timer object which you can use in `cancel-timer'."
397 (interactive "sRun after delay (seconds): \nNRepeat interval: \naFunction: ")
398 (apply 'run-at-time secs repeat function args))
400 (defun add-timeout (secs function object &optional repeat)
401 "Add a timer to run SECS seconds from now, to call FUNCTION on OBJECT.
402 If REPEAT is non-nil, repeat the timer every REPEAT seconds.
403 This function is for compatibility; see also `run-with-timer'."
404 (run-with-timer secs repeat function object))
406 (defun run-with-idle-timer (secs repeat function &rest args)
407 "Perform an action the next time Emacs is idle for SECS seconds.
408 The action is to call FUNCTION with arguments ARGS.
409 SECS may be an integer, a floating point number, or the internal
410 time format returned by, e.g., `current-idle-time'.
411 If Emacs is currently idle, and has been idle for N seconds (N < SECS),
412 then it will call FUNCTION in SECS - N seconds from now. Using
413 SECS <= N is not recommended if this function is invoked from an idle
414 timer, because FUNCTION will then be called immediately.
416 If REPEAT is non-nil, do the action each time Emacs has been idle for
417 exactly SECS seconds (that is, only once for each time Emacs becomes idle).
419 This function returns a timer object which you can use in `cancel-timer'."
420 (interactive
421 (list (read-from-minibuffer "Run after idle (seconds): " nil nil t)
422 (y-or-n-p "Repeat each time Emacs is idle? ")
423 (intern (completing-read "Function: " obarray 'fboundp t))))
424 (let ((timer (timer-create)))
425 (timer-set-function timer function args)
426 (timer-set-idle-time timer secs repeat)
427 (timer-activate-when-idle timer t)
428 timer))
430 (defvar with-timeout-timers nil
431 "List of all timers used by currently pending `with-timeout' calls.")
433 (defmacro with-timeout (list &rest body)
434 "Run BODY, but if it doesn't finish in SECONDS seconds, give up.
435 If we give up, we run the TIMEOUT-FORMS and return the value of the last one.
436 The timeout is checked whenever Emacs waits for some kind of external
437 event (such as keyboard input, input from subprocesses, or a certain time);
438 if the program loops without waiting in any way, the timeout will not
439 be detected.
440 \n(fn (SECONDS TIMEOUT-FORMS...) BODY)"
441 (declare (indent 1) (debug ((form body) body)))
442 (let ((seconds (car list))
443 (timeout-forms (cdr list))
444 (timeout (make-symbol "timeout")))
445 `(let ((-with-timeout-value-
446 (catch ',timeout
447 (let* ((-with-timeout-timer-
448 (run-with-timer ,seconds nil
449 (lambda () (throw ',timeout ',timeout))))
450 (with-timeout-timers
451 (cons -with-timeout-timer- with-timeout-timers)))
452 (unwind-protect
453 (progn ,@body)
454 (cancel-timer -with-timeout-timer-))))))
455 ;; It is tempting to avoid the `if' altogether and instead run
456 ;; timeout-forms in the timer, just before throwing `timeout'.
457 ;; But that would mean that timeout-forms are run in the deeper
458 ;; dynamic context of the timer, with inhibit-quit set etc...
459 (if (eq -with-timeout-value- ',timeout)
460 (progn ,@timeout-forms)
461 -with-timeout-value-))))
463 (defun with-timeout-suspend ()
464 "Stop the clock for `with-timeout'. Used by debuggers.
465 The idea is that the time you spend in the debugger should not
466 count against these timeouts.
468 The value is a list that the debugger can pass to `with-timeout-unsuspend'
469 when it exits, to make these timers start counting again."
470 (mapcar (lambda (timer)
471 (cancel-timer timer)
472 (list timer (time-subtract (timer--time timer) (current-time))))
473 with-timeout-timers))
475 (defun with-timeout-unsuspend (timer-spec-list)
476 "Restart the clock for `with-timeout'.
477 The argument should be a value previously returned by `with-timeout-suspend'."
478 (dolist (elt timer-spec-list)
479 (let ((timer (car elt))
480 (delay (cadr elt)))
481 (timer-set-time timer (time-add (current-time) delay))
482 (timer-activate timer))))
484 (defun y-or-n-p-with-timeout (prompt seconds default-value)
485 "Like (y-or-n-p PROMPT), with a timeout.
486 If the user does not answer after SECONDS seconds, return DEFAULT-VALUE."
487 (with-timeout (seconds default-value)
488 (y-or-n-p prompt)))
490 (defconst timer-duration-words
491 (list (cons "microsec" 0.000001)
492 (cons "microsecond" 0.000001)
493 (cons "millisec" 0.001)
494 (cons "millisecond" 0.001)
495 (cons "sec" 1)
496 (cons "second" 1)
497 (cons "min" 60)
498 (cons "minute" 60)
499 (cons "hour" (* 60 60))
500 (cons "day" (* 24 60 60))
501 (cons "week" (* 7 24 60 60))
502 (cons "fortnight" (* 14 24 60 60))
503 (cons "month" (* 30 24 60 60)) ; Approximation
504 (cons "year" (* 365.25 24 60 60)) ; Approximation
506 "Alist mapping temporal words to durations in seconds.")
508 (defun timer-duration (string)
509 "Return number of seconds specified by STRING, or nil if parsing fails."
510 (let ((secs 0)
511 (start 0)
512 (case-fold-search t))
513 (while (string-match
514 "[ \t]*\\([0-9.]+\\)?[ \t]*\\([a-z]+[a-rt-z]\\)s?[ \t]*"
515 string start)
516 (let ((count (if (match-beginning 1)
517 (string-to-number (match-string 1 string))
519 (itemsize (cdr (assoc (match-string 2 string)
520 timer-duration-words))))
521 (if itemsize
522 (setq start (match-end 0)
523 secs (+ secs (* count itemsize)))
524 (setq secs nil
525 start (length string)))))
526 (if (= start (length string))
527 secs
528 (if (string-match-p "\\`[0-9.]+\\'" string)
529 (string-to-number string)))))
531 (provide 'timer)
533 ;;; timer.el ends here