1 ;;; timer.el --- run a function with args at some time in future
3 ;; Copyright (C) 1996, 2002, 2003, 2004, 2005,
4 ;; 2006 Free Software Foundation, Inc.
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 2, or (at your option)
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; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23 ;; Boston, MA 02110-1301, USA.
27 ;; This package gives you the capability to run Emacs Lisp commands at
28 ;; specified times in the future, either as one-shots or periodically.
32 ;; Layout of a timer vector:
33 ;; [triggered-p high-seconds low-seconds usecs repeat-delay
34 ;; function args idle-delay]
36 (defun timer-create ()
37 "Create a timer object."
38 (let ((timer (make-vector 8 nil)))
42 (defun timerp (object)
43 "Return t if OBJECT is a timer."
44 (and (vectorp object) (= (length object) 8)))
46 (defun timer-set-time (timer time &optional delta)
47 "Set the trigger time of TIMER to TIME.
48 TIME must be in the internal format returned by, e.g., `current-time'.
49 If optional third argument DELTA is a positive number, make the timer
50 fire repeatedly that many seconds apart."
52 (error "Invalid timer"))
53 (aset timer 1 (car time))
54 (aset timer 2 (if (consp (cdr time)) (car (cdr time)) (cdr time)))
55 (aset timer 3 (or (and (consp (cdr time)) (consp (cdr (cdr time)))
58 (aset timer 4 (and (numberp delta) (> delta 0) delta))
61 (defun timer-set-idle-time (timer secs &optional repeat)
62 "Set the trigger idle time of TIMER to SECS.
63 SECS may be an integer, floating point number, or the internal
64 time format (HIGH LOW USECS) returned by, e.g., `current-idle-time'.
65 If optional third argument REPEAT is non-nil, make the timer
66 fire each time Emacs is idle for that many seconds."
68 (error "Invalid timer"))
70 (progn (aset timer 1 (car secs))
71 (aset timer 2 (if (consp (cdr secs)) (car (cdr secs)) (cdr secs)))
72 (aset timer 3 (or (and (consp (cdr secs)) (consp (cdr (cdr secs)))
78 (timer-inc-time timer secs))
82 (defun timer-next-integral-multiple-of-time (time secs)
83 "Yield the next value after TIME that is an integral multiple of SECS.
84 More precisely, the next value, after TIME, that is an integral multiple
85 of SECS seconds since the epoch. SECS may be a fraction."
86 (let ((time-base (ash 1 16)))
88 ;; Use floating point, taking care to not lose precision.
89 (let* ((float-time-base (float time-base))
91 (time-usec (+ (* million
92 (+ (* float-time-base (nth 0 time))
95 (secs-usec (* million secs))
96 (mod-usec (mod time-usec secs-usec))
97 (next-usec (+ (- time-usec mod-usec) secs-usec))
98 (time-base-million (* float-time-base million)))
99 (list (floor next-usec time-base-million)
100 (floor (mod next-usec time-base-million) million)
101 (floor (mod next-usec million))))
102 ;; Floating point is not supported.
103 ;; Use integer arithmetic, avoiding overflow if possible.
104 (let* ((mod-sec (mod (+ (* (mod time-base secs)
105 (mod (nth 0 time) secs))
108 (next-1-sec (+ (- (nth 1 time) mod-sec) secs)))
109 (list (+ (nth 0 time) (floor next-1-sec time-base))
110 (mod next-1-sec time-base)
113 (defun timer-relative-time (time secs &optional usecs)
114 "Advance TIME by SECS seconds and optionally USECS microseconds.
115 SECS may be either an integer or a floating point number."
116 (let ((high (car time))
117 (low (if (consp (cdr time)) (nth 1 time) (cdr time)))
118 (micro (if (numberp (car-safe (cdr-safe (cdr time))))
122 (if usecs (setq micro (+ micro usecs)))
124 (setq micro (+ micro (floor (* 1000000 (- secs (floor secs)))))))
125 (setq low (+ low (floor secs)))
128 ;; `/' rounds towards zero while `mod' returns a positive number,
129 ;; so we can't rely on (= a (+ (* 100 (/ a 100)) (mod a 100))).
130 (setq low (+ low (/ micro 1000000) (if (< micro 0) -1 0)))
131 (setq micro (mod micro 1000000))
132 (setq high (+ high (/ low 65536) (if (< low 0) -1 0)))
133 (setq low (logand low 65535))
135 (list high low (and (/= micro 0) micro))))
137 (defun timer-inc-time (timer secs &optional usecs)
138 "Increment the time set in TIMER by SECS seconds and USECS microseconds.
139 SECS may be a fraction. If USECS is omitted, that means it is zero."
140 (let ((time (timer-relative-time
141 (list (aref timer 1) (aref timer 2) (aref timer 3))
144 (aset timer 1 (nth 0 time))
145 (aset timer 2 (nth 1 time))
146 (aset timer 3 (or (nth 2 time) 0))))
148 (defun timer-set-time-with-usecs (timer time usecs &optional delta)
149 "Set the trigger time of TIMER to TIME plus USECS.
150 TIME must be in the internal format returned by, e.g., `current-time'.
151 The microsecond count from TIME is ignored, and USECS is used instead.
152 If optional fourth argument DELTA is a positive number, make the timer
153 fire repeatedly that many seconds apart."
155 (error "Invalid timer"))
156 (aset timer 1 (nth 0 time))
157 (aset timer 2 (nth 1 time))
159 (aset timer 4 (and (numberp delta) (> delta 0) delta))
161 (make-obsolete 'timer-set-time-with-usecs
162 "use `timer-set-time' and `timer-inc-time' instead."
165 (defun timer-set-function (timer function &optional args)
166 "Make TIMER call FUNCTION with optional ARGS when triggering."
168 (error "Invalid timer"))
169 (aset timer 5 function)
173 (defun timer-activate (timer &optional triggered-p reuse-cell)
174 "Put TIMER on the list of active timers.
176 REUSE-CELL, if non-nil, is a cons cell to reuse instead
177 of allocating a new one."
178 (if (and (timerp timer)
179 (integerp (aref timer 1))
180 (integerp (aref timer 2))
181 (integerp (aref timer 3))
183 (let ((timers timer-list)
185 ;; Skip all timers to trigger before the new one.
187 (or (> (aref timer 1) (aref (car timers) 1))
188 (and (= (aref timer 1) (aref (car timers) 1))
189 (> (aref timer 2) (aref (car timers) 2)))
190 (and (= (aref timer 1) (aref (car timers) 1))
191 (= (aref timer 2) (aref (car timers) 2))
192 (> (aref timer 3) (aref (car timers) 3)))))
194 timers (cdr timers)))
197 (setcar reuse-cell timer)
198 (setcdr reuse-cell timers))
199 (setq reuse-cell (cons timer timers)))
200 ;; Insert new timer after last which possibly means in front of queue.
202 (setcdr last reuse-cell)
203 (setq timer-list reuse-cell))
204 (aset timer 0 triggered-p)
207 (error "Invalid or uninitialized timer")))
209 (defun timer-activate-when-idle (timer &optional dont-wait reuse-cell)
210 "Arrange to activate TIMER whenever Emacs is next idle.
211 If optional argument DONT-WAIT is non-nil, then enable the
212 timer to activate immediately, or at the right time, if Emacs
215 REUSE-CELL, if non-nil, is a cons cell to reuse instead
216 of allocating a new one."
217 (if (and (timerp timer)
218 (integerp (aref timer 1))
219 (integerp (aref timer 2))
220 (integerp (aref timer 3))
222 (let ((timers timer-idle-list)
224 ;; Skip all timers to trigger before the new one.
226 (or (> (aref timer 1) (aref (car timers) 1))
227 (and (= (aref timer 1) (aref (car timers) 1))
228 (> (aref timer 2) (aref (car timers) 2)))
229 (and (= (aref timer 1) (aref (car timers) 1))
230 (= (aref timer 2) (aref (car timers) 2))
231 (> (aref timer 3) (aref (car timers) 3)))))
233 timers (cdr timers)))
236 (setcar reuse-cell timer)
237 (setcdr reuse-cell timers))
238 (setq reuse-cell (cons timer timers)))
239 ;; Insert new timer after last which possibly means in front of queue.
241 (setcdr last reuse-cell)
242 (setq timer-idle-list reuse-cell))
243 (aset timer 0 (not dont-wait))
246 (error "Invalid or uninitialized timer")))
249 (defalias 'disable-timeout 'cancel-timer)
251 (defun cancel-timer (timer)
252 "Remove TIMER from the list of active timers."
254 (error "Invalid timer"))
255 (setq timer-list (delq timer timer-list))
256 (setq timer-idle-list (delq timer timer-idle-list))
259 ;; Remove TIMER from the list of active timers or idle timers.
260 ;; Only to be used in this file. It returns the cons cell
261 ;; that was removed from the list.
262 (defun cancel-timer-internal (timer)
263 (let ((cell1 (memq timer timer-list))
264 (cell2 (memq timer timer-idle-list)))
266 (setq timer-list (delq timer timer-list)))
268 (setq timer-idle-list (delq timer timer-idle-list)))
272 (defun cancel-function-timers (function)
273 "Cancel all timers scheduled by `run-at-time' which would run FUNCTION."
274 (interactive "aCancel timers of function: ")
275 (let ((tail timer-list))
277 (if (eq (aref (car tail) 5) function)
278 (setq timer-list (delq (car tail) timer-list)))
279 (setq tail (cdr tail))))
280 (let ((tail timer-idle-list))
282 (if (eq (aref (car tail) 5) function)
283 (setq timer-idle-list (delq (car tail) timer-idle-list)))
284 (setq tail (cdr tail)))))
286 ;; Record the last few events, for debugging.
287 (defvar timer-event-last-2 nil)
288 (defvar timer-event-last-1 nil)
289 (defvar timer-event-last nil)
291 (defvar timer-max-repeats 10
292 "*Maximum number of times to repeat a timer, if real time jumps.")
294 (defun timer-until (timer time)
295 "Calculate number of seconds from when TIMER will run, until TIME.
296 TIMER is a timer, and stands for the time when its next repeat is scheduled.
297 TIME is a time-list."
298 (let ((high (- (car time) (aref timer 1)))
299 (low (- (nth 1 time) (aref timer 2))))
300 (+ low (* high 65536))))
302 (defun timer-event-handler (timer)
303 "Call the handler for the timer TIMER.
304 This function is called, by name, directly by the C code."
305 (setq timer-event-last-2 timer-event-last-1)
306 (setq timer-event-last-1 timer-event-last)
307 (setq timer-event-last timer)
308 (let ((inhibit-quit t))
310 (let (retrigger cell)
311 ;; Delete from queue. Record the cons cell that was used.
312 (setq cell (cancel-timer-internal timer))
313 ;; Re-schedule if requested.
316 (timer-activate-when-idle timer nil cell)
317 (timer-inc-time timer (aref timer 4) 0)
318 ;; If real time has jumped forward,
319 ;; perhaps because Emacs was suspended for a long time,
320 ;; limit how many times things get repeated.
321 (if (and (numberp timer-max-repeats)
322 (< 0 (timer-until timer (current-time))))
323 (let ((repeats (/ (timer-until timer (current-time))
325 (if (> repeats timer-max-repeats)
326 (timer-inc-time timer (* (aref timer 4) repeats)))))
327 (timer-activate timer t cell)
330 ;; We do this after rescheduling so that the handler function
331 ;; can cancel its own timer successfully with cancel-timer.
333 (apply (aref timer 5) (aref timer 6))
337 (error "Bogus timer event"))))
339 ;; This function is incompatible with the one in levents.el.
340 (defun timeout-event-p (event)
341 "Non-nil if EVENT is a timeout event."
342 (and (listp event) (eq (car event) 'timer-event)))
345 (defun run-at-time (time repeat function &rest args)
346 "Perform an action at time TIME.
347 Repeat the action every REPEAT seconds, if REPEAT is non-nil.
348 TIME should be a string like \"11:23pm\", nil meaning now, a number of seconds
349 from now, a value from `current-time', or t (with non-nil REPEAT)
350 meaning the next integral multiple of REPEAT.
351 REPEAT may be an integer or floating point number.
352 The action is to call FUNCTION with arguments ARGS.
354 This function returns a timer object which you can use in `cancel-timer'."
355 (interactive "sRun at time: \nNRepeat interval: \naFunction: ")
358 (and (numberp repeat) (< 0 repeat))
359 (error "Invalid repetition interval"))
361 ;; Special case: nil means "now" and is useful when repeating.
363 (setq time (current-time)))
365 ;; Special case: t means the next integral multiple of REPEAT.
366 (if (and (eq time t) repeat)
367 (setq time (timer-next-integral-multiple-of-time (current-time) repeat)))
369 ;; Handle numbers as relative times in seconds.
371 (setq time (timer-relative-time (current-time) time)))
373 ;; Handle relative times like "2 hours and 35 minutes"
375 (let ((secs (timer-duration time)))
377 (setq time (timer-relative-time (current-time) secs)))))
379 ;; Handle "11:23pm" and the like. Interpret it as meaning today
380 ;; which admittedly is rather stupid if we have passed that time
381 ;; already. (Though only Emacs hackers hack Emacs at that time.)
385 (let ((hhmm (diary-entry-time time))
389 (encode-time 0 (% hhmm 100) (/ hhmm 100) (nth 3 now)
390 (nth 4 now) (nth 5 now) (nth 8 now)))))))
393 (error "Invalid time format"))
395 (let ((timer (timer-create)))
396 (timer-set-time timer time repeat)
397 (timer-set-function timer function args)
398 (timer-activate timer)
402 (defun run-with-timer (secs repeat function &rest args)
403 "Perform an action after a delay of SECS seconds.
404 Repeat the action every REPEAT seconds, if REPEAT is non-nil.
405 SECS and REPEAT may be integers or floating point numbers.
406 The action is to call FUNCTION with arguments ARGS.
408 This function returns a timer object which you can use in `cancel-timer'."
409 (interactive "sRun after delay (seconds): \nNRepeat interval: \naFunction: ")
410 (apply 'run-at-time secs repeat function args))
413 (defun add-timeout (secs function object &optional repeat)
414 "Add a timer to run SECS seconds from now, to call FUNCTION on OBJECT.
415 If REPEAT is non-nil, repeat the timer every REPEAT seconds.
416 This function is for compatibility; see also `run-with-timer'."
417 (run-with-timer secs repeat function object))
420 (defun run-with-idle-timer (secs repeat function &rest args)
421 "Perform an action the next time Emacs is idle for SECS seconds.
422 The action is to call FUNCTION with arguments ARGS.
423 SECS may be an integer, a floating point number, or the internal
424 time format (HIGH LOW USECS) returned by, e.g., `current-idle-time'.
425 If Emacs is currently idle, and has been idle for N seconds (N < SECS),
426 then it will call FUNCTION in SECS - N seconds from now.
428 If REPEAT is non-nil, do the action each time Emacs has been idle for
429 exactly SECS seconds (that is, only once for each time Emacs becomes idle).
431 This function returns a timer object which you can use in `cancel-timer'."
433 (list (read-from-minibuffer "Run after idle (seconds): " nil nil t)
434 (y-or-n-p "Repeat each time Emacs is idle? ")
435 (intern (completing-read "Function: " obarray 'fboundp t))))
436 (let ((timer (timer-create)))
437 (timer-set-function timer function args)
438 (timer-set-idle-time timer secs repeat)
439 (timer-activate-when-idle timer t)
442 (defun with-timeout-handler (tag)
443 (throw tag 'timeout))
445 ;;;###autoload (put 'with-timeout 'lisp-indent-function 1)
447 (defvar with-timeout-timers nil
448 "List of all timers used by currently pending `with-timeout' calls.")
451 (defmacro with-timeout (list &rest body)
452 "Run BODY, but if it doesn't finish in SECONDS seconds, give up.
453 If we give up, we run the TIMEOUT-FORMS and return the value of the last one.
454 The timeout is checked whenever Emacs waits for some kind of external
455 event (such as keyboard input, input from subprocesses, or a certain time);
456 if the program loops without waiting in any way, the timeout will not
458 \n(fn (SECONDS TIMEOUT-FORMS...) BODY)"
459 (let ((seconds (car list))
460 (timeout-forms (cdr list)))
461 `(let ((with-timeout-tag (cons nil nil))
462 with-timeout-value with-timeout-timer
463 (with-timeout-timers with-timeout-timers))
464 (if (catch with-timeout-tag
466 (setq with-timeout-timer
467 (run-with-timer ,seconds nil
468 'with-timeout-handler
470 (push with-timeout-timer with-timeout-timers)
471 (setq with-timeout-value (progn . ,body))
473 (progn . ,timeout-forms)
474 (cancel-timer with-timeout-timer)
475 with-timeout-value))))
477 (defun with-timeout-suspend ()
478 "Stop the clock for `with-timeout'. Used by debuggers.
479 The idea is that the time you spend in the debugger should not
480 count against these timeouts.
482 The value is a list that the debugger can pass to `with-timeout-unsuspend'
483 when it exits, to make these timers start counting again."
484 (mapcar (lambda (timer)
488 ;; The time that this timer will go off.
489 (list (aref timer 1) (aref timer 2) (aref timer 3))
491 with-timeout-timers))
493 (defun with-timeout-unsuspend (timer-spec-list)
494 "Restart the clock for `with-timeout'.
495 The argument should be a value previously returned by `with-timeout-suspend'."
496 (dolist (elt timer-spec-list)
497 (let ((timer (car elt))
499 (timer-set-time timer (time-add (current-time) delay))
500 (timer-activate timer))))
502 (defun y-or-n-p-with-timeout (prompt seconds default-value)
503 "Like (y-or-n-p PROMPT), with a timeout.
504 If the user does not answer after SECONDS seconds, return DEFAULT-VALUE."
505 (with-timeout (seconds default-value)
508 (defvar timer-duration-words
509 (list (cons "microsec" 0.000001)
510 (cons "microsecond" 0.000001)
511 (cons "millisec" 0.001)
512 (cons "millisecond" 0.001)
517 (cons "hour" (* 60 60))
518 (cons "day" (* 24 60 60))
519 (cons "week" (* 7 24 60 60))
520 (cons "fortnight" (* 14 24 60 60))
521 (cons "month" (* 30 24 60 60)) ; Approximation
522 (cons "year" (* 365.25 24 60 60)) ; Approximation
524 "Alist mapping temporal words to durations in seconds")
526 (defun timer-duration (string)
527 "Return number of seconds specified by STRING, or nil if parsing fails."
530 (case-fold-search t))
532 "[ \t]*\\([0-9.]+\\)?[ \t]*\\([a-z]+[a-rt-z]\\)s?[ \t]*"
534 (let ((count (if (match-beginning 1)
535 (string-to-number (match-string 1 string))
537 (itemsize (cdr (assoc (match-string 2 string)
538 timer-duration-words))))
540 (setq start (match-end 0)
541 secs (+ secs (* count itemsize)))
543 start (length string)))))
544 (if (= start (length string))
546 (if (string-match "\\`[0-9.]+\\'" string)
547 (string-to-number string)))))
551 ;;; arch-tag: b1a9237b-7787-4382-9e46-8f2c3b3273e0
552 ;;; timer.el ends here