1 ;;; timer.el --- run a function with args at some time in future
3 ;; Copyright (C) 1996, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
7 ;; This file is part of GNU Emacs.
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING. If not, write to the
21 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22 ;; Boston, MA 02110-1301, USA.
26 ;; This package gives you the capability to run Emacs Lisp commands at
27 ;; specified times in the future, either as one-shots or periodically.
31 ;; Layout of a timer vector:
32 ;; [triggered-p high-seconds low-seconds usecs repeat-delay
33 ;; function args idle-delay]
35 (defun timer-create ()
36 "Create a timer object."
37 (let ((timer (make-vector 8 nil)))
41 (defun timerp (object)
42 "Return t if OBJECT is a timer."
43 (and (vectorp object) (= (length object) 8)))
45 (defun timer-set-time (timer time &optional delta)
46 "Set the trigger time of TIMER to TIME.
47 TIME must be in the internal format returned by, e.g., `current-time'.
48 If optional third argument DELTA is a positive number, make the timer
49 fire repeatedly that many seconds apart."
51 (error "Invalid timer"))
52 (aset timer 1 (car time))
53 (aset timer 2 (if (consp (cdr time)) (car (cdr time)) (cdr time)))
54 (aset timer 3 (or (and (consp (cdr time)) (consp (cdr (cdr time)))
57 (aset timer 4 (and (numberp delta) (> delta 0) delta))
60 (defun timer-set-idle-time (timer secs &optional repeat)
61 "Set the trigger idle time of TIMER to SECS.
62 If optional third argument REPEAT is non-nil, make the timer
63 fire each time Emacs is idle for that many seconds."
65 (error "Invalid timer"))
69 (timer-inc-time timer secs)
73 (defun timer-next-integral-multiple-of-time (time secs)
74 "Yield the next value after TIME that is an integral multiple of SECS.
75 More precisely, the next value, after TIME, that is an integral multiple
76 of SECS seconds since the epoch. SECS may be a fraction."
77 (let ((time-base (ash 1 16)))
79 ;; Use floating point, taking care to not lose precision.
80 (let* ((float-time-base (float time-base))
82 (time-usec (+ (* million
83 (+ (* float-time-base (nth 0 time))
86 (secs-usec (* million secs))
87 (mod-usec (mod time-usec secs-usec))
88 (next-usec (+ (- time-usec mod-usec) secs-usec))
89 (time-base-million (* float-time-base million)))
90 (list (floor next-usec time-base-million)
91 (floor (mod next-usec time-base-million) million)
92 (floor (mod next-usec million))))
93 ;; Floating point is not supported.
94 ;; Use integer arithmetic, avoiding overflow if possible.
95 (let* ((mod-sec (mod (+ (* (mod time-base secs)
96 (mod (nth 0 time) secs))
99 (next-1-sec (+ (- (nth 1 time) mod-sec) secs)))
100 (list (+ (nth 0 time) (floor next-1-sec time-base))
101 (mod next-1-sec time-base)
104 (defun timer-relative-time (time secs &optional usecs)
105 "Advance TIME by SECS seconds and optionally USECS microseconds.
106 SECS may be a fraction."
107 (let ((high (car time))
108 (low (if (consp (cdr time)) (nth 1 time) (cdr time)))
109 (micro (if (numberp (car-safe (cdr-safe (cdr time))))
113 (if usecs (setq micro (+ micro usecs)))
115 (setq micro (+ micro (floor (* 1000000 (- secs (floor secs)))))))
116 (setq low (+ low (floor secs)))
119 ;; `/' rounds towards zero while `mod' returns a positive number,
120 ;; so we can't rely on (= a (+ (* 100 (/ a 100)) (mod a 100))).
121 (setq low (+ low (/ micro 1000000) (if (< micro 0) -1 0)))
122 (setq micro (mod micro 1000000))
123 (setq high (+ high (/ low 65536) (if (< low 0) -1 0)))
124 (setq low (logand low 65535))
126 (list high low (and (/= micro 0) micro))))
128 (defun timer-inc-time (timer secs &optional usecs)
129 "Increment the time set in TIMER by SECS seconds and USECS microseconds.
130 SECS may be a fraction. If USECS is omitted, that means it is zero."
131 (let ((time (timer-relative-time
132 (list (aref timer 1) (aref timer 2) (aref timer 3))
135 (aset timer 1 (nth 0 time))
136 (aset timer 2 (nth 1 time))
137 (aset timer 3 (or (nth 2 time) 0))))
139 (defun timer-set-time-with-usecs (timer time usecs &optional delta)
140 "Set the trigger time of TIMER to TIME plus USECS.
141 TIME must be in the internal format returned by, e.g., `current-time'.
142 The microsecond count from TIME is ignored, and USECS is used instead.
143 If optional fourth argument DELTA is a positive number, make the timer
144 fire repeatedly that many seconds apart."
146 (error "Invalid timer"))
147 (aset timer 1 (nth 0 time))
148 (aset timer 2 (nth 1 time))
150 (aset timer 4 (and (numberp delta) (> delta 0) delta))
152 (make-obsolete 'timer-set-time-with-usecs
153 "use `timer-set-time' and `timer-inc-time' instead."
156 (defun timer-set-function (timer function &optional args)
157 "Make TIMER call FUNCTION with optional ARGS when triggering."
159 (error "Invalid timer"))
160 (aset timer 5 function)
164 (defun timer-activate (timer &optional triggered-p reuse-cell)
165 "Put TIMER on the list of active timers.
167 REUSE-CELL, if non-nil, is a cons cell to reuse instead
168 of allocating a new one."
169 (if (and (timerp timer)
170 (integerp (aref timer 1))
171 (integerp (aref timer 2))
172 (integerp (aref timer 3))
174 (let ((timers timer-list)
176 ;; Skip all timers to trigger before the new one.
178 (or (> (aref timer 1) (aref (car timers) 1))
179 (and (= (aref timer 1) (aref (car timers) 1))
180 (> (aref timer 2) (aref (car timers) 2)))
181 (and (= (aref timer 1) (aref (car timers) 1))
182 (= (aref timer 2) (aref (car timers) 2))
183 (> (aref timer 3) (aref (car timers) 3)))))
185 timers (cdr timers)))
188 (setcar reuse-cell timer)
189 (setcdr reuse-cell timers))
190 (setq reuse-cell (cons timer timers)))
191 ;; Insert new timer after last which possibly means in front of queue.
193 (setcdr last reuse-cell)
194 (setq timer-list reuse-cell))
195 (aset timer 0 triggered-p)
198 (error "Invalid or uninitialized timer")))
200 (defun timer-activate-when-idle (timer &optional dont-wait reuse-cell)
201 "Arrange to activate TIMER whenever Emacs is next idle.
202 If optional argument DONT-WAIT is non-nil, then enable the
203 timer to activate immediately, or at the right time, if Emacs
206 REUSE-CELL, if non-nil, is a cons cell to reuse instead
207 of allocating a new one."
208 (if (and (timerp timer)
209 (integerp (aref timer 1))
210 (integerp (aref timer 2))
211 (integerp (aref timer 3))
213 (let ((timers timer-idle-list)
215 ;; Skip all timers to trigger before the new one.
217 (or (> (aref timer 1) (aref (car timers) 1))
218 (and (= (aref timer 1) (aref (car timers) 1))
219 (> (aref timer 2) (aref (car timers) 2)))
220 (and (= (aref timer 1) (aref (car timers) 1))
221 (= (aref timer 2) (aref (car timers) 2))
222 (> (aref timer 3) (aref (car timers) 3)))))
224 timers (cdr timers)))
227 (setcar reuse-cell timer)
228 (setcdr reuse-cell timers))
229 (setq reuse-cell (cons timer timers)))
230 ;; Insert new timer after last which possibly means in front of queue.
232 (setcdr last reuse-cell)
233 (setq timer-idle-list reuse-cell))
234 (aset timer 0 (not dont-wait))
237 (error "Invalid or uninitialized timer")))
240 (defalias 'disable-timeout 'cancel-timer)
242 (defun cancel-timer (timer)
243 "Remove TIMER from the list of active timers."
245 (error "Invalid timer"))
246 (setq timer-list (delq timer timer-list))
247 (setq timer-idle-list (delq timer timer-idle-list))
250 ;; Remove TIMER from the list of active timers or idle timers.
251 ;; Only to be used in this file. It returns the cons cell
252 ;; that was removed from the list.
253 (defun cancel-timer-internal (timer)
254 (let ((cell1 (memq timer timer-list))
255 (cell2 (memq timer timer-idle-list)))
257 (setq timer-list (delq timer timer-list)))
259 (setq timer-idle-list (delq timer timer-idle-list)))
263 (defun cancel-function-timers (function)
264 "Cancel all timers scheduled by `run-at-time' which would run FUNCTION."
265 (interactive "aCancel timers of function: ")
266 (let ((tail timer-list))
268 (if (eq (aref (car tail) 5) function)
269 (setq timer-list (delq (car tail) timer-list)))
270 (setq tail (cdr tail))))
271 (let ((tail timer-idle-list))
273 (if (eq (aref (car tail) 5) function)
274 (setq timer-idle-list (delq (car tail) timer-idle-list)))
275 (setq tail (cdr tail)))))
277 ;; Record the last few events, for debugging.
278 (defvar timer-event-last-2 nil)
279 (defvar timer-event-last-1 nil)
280 (defvar timer-event-last nil)
282 (defvar timer-max-repeats 10
283 "*Maximum number of times to repeat a timer, if real time jumps.")
285 (defun timer-until (timer time)
286 "Calculate number of seconds from when TIMER will run, until TIME.
287 TIMER is a timer, and stands for the time when its next repeat is scheduled.
288 TIME is a time-list."
289 (let ((high (- (car time) (aref timer 1)))
290 (low (- (nth 1 time) (aref timer 2))))
291 (+ low (* high 65536))))
293 (defun timer-event-handler (timer)
294 "Call the handler for the timer TIMER.
295 This function is called, by name, directly by the C code."
296 (setq timer-event-last-2 timer-event-last-1)
297 (setq timer-event-last-1 timer-event-last)
298 (setq timer-event-last timer)
299 (let ((inhibit-quit t))
301 (let (retrigger cell)
302 ;; Delete from queue. Record the cons cell that was used.
303 (setq cell (cancel-timer-internal timer))
304 ;; Re-schedule if requested.
307 (timer-activate-when-idle timer nil cell)
308 (timer-inc-time timer (aref timer 4) 0)
309 ;; If real time has jumped forward,
310 ;; perhaps because Emacs was suspended for a long time,
311 ;; limit how many times things get repeated.
312 (if (and (numberp timer-max-repeats)
313 (< 0 (timer-until timer (current-time))))
314 (let ((repeats (/ (timer-until timer (current-time))
316 (if (> repeats timer-max-repeats)
317 (timer-inc-time timer (* (aref timer 4) repeats)))))
318 (timer-activate timer t cell)
321 ;; We do this after rescheduling so that the handler function
322 ;; can cancel its own timer successfully with cancel-timer.
324 (apply (aref timer 5) (aref timer 6))
328 (error "Bogus timer event"))))
330 ;; This function is incompatible with the one in levents.el.
331 (defun timeout-event-p (event)
332 "Non-nil if EVENT is a timeout event."
333 (and (listp event) (eq (car event) 'timer-event)))
336 (defun run-at-time (time repeat function &rest args)
337 "Perform an action at time TIME.
338 Repeat the action every REPEAT seconds, if REPEAT is non-nil.
339 TIME should be a string like \"11:23pm\", nil meaning now, a number of seconds
340 from now, a value from `current-time', or t (with non-nil REPEAT)
341 meaning the next integral multiple of REPEAT.
342 REPEAT may be an integer or floating point number.
343 The action is to call FUNCTION with arguments ARGS.
345 This function returns a timer object which you can use in `cancel-timer'."
346 (interactive "sRun at time: \nNRepeat interval: \naFunction: ")
349 (and (numberp repeat) (< 0 repeat))
350 (error "Invalid repetition interval"))
352 ;; Special case: nil means "now" and is useful when repeating.
354 (setq time (current-time)))
356 ;; Special case: t means the next integral multiple of REPEAT.
357 (if (and (eq time t) repeat)
358 (setq time (timer-next-integral-multiple-of-time (current-time) repeat)))
360 ;; Handle numbers as relative times in seconds.
362 (setq time (timer-relative-time (current-time) time)))
364 ;; Handle relative times like "2 hours and 35 minutes"
366 (let ((secs (timer-duration time)))
368 (setq time (timer-relative-time (current-time) secs)))))
370 ;; Handle "11:23pm" and the like. Interpret it as meaning today
371 ;; which admittedly is rather stupid if we have passed that time
372 ;; already. (Though only Emacs hackers hack Emacs at that time.)
376 (let ((hhmm (diary-entry-time time))
380 (encode-time 0 (% hhmm 100) (/ hhmm 100) (nth 3 now)
381 (nth 4 now) (nth 5 now) (nth 8 now)))))))
384 (error "Invalid time format"))
386 (let ((timer (timer-create)))
387 (timer-set-time timer time repeat)
388 (timer-set-function timer function args)
389 (timer-activate timer)
393 (defun run-with-timer (secs repeat function &rest args)
394 "Perform an action after a delay of SECS seconds.
395 Repeat the action every REPEAT seconds, if REPEAT is non-nil.
396 SECS and REPEAT may be integers or floating point numbers.
397 The action is to call FUNCTION with arguments ARGS.
399 This function returns a timer object which you can use in `cancel-timer'."
400 (interactive "sRun after delay (seconds): \nNRepeat interval: \naFunction: ")
401 (apply 'run-at-time secs repeat function args))
404 (defun add-timeout (secs function object &optional repeat)
405 "Add a timer to run SECS seconds from now, to call FUNCTION on OBJECT.
406 If REPEAT is non-nil, repeat the timer every REPEAT seconds.
407 This function is for compatibility; see also `run-with-timer'."
408 (run-with-timer secs repeat function object))
411 (defun run-with-idle-timer (secs repeat function &rest args)
412 "Perform an action the next time Emacs is idle for SECS seconds.
413 The action is to call FUNCTION with arguments ARGS.
414 SECS may be an integer or a floating point number.
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'."
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)
430 (defun with-timeout-handler (tag)
431 (throw tag 'timeout))
433 ;;;###autoload (put 'with-timeout 'lisp-indent-function 1)
435 (defvar with-timeout-timers nil
436 "List of all timers used by currently pending `with-timeout' calls.")
439 (defmacro with-timeout (list &rest body)
440 "Run BODY, but if it doesn't finish in SECONDS seconds, give up.
441 If we give up, we run the TIMEOUT-FORMS and return the value of the last one.
442 The timeout is checked whenever Emacs waits for some kind of external
443 event (such as keyboard input, input from subprocesses, or a certain time);
444 if the program loops without waiting in any way, the timeout will not
446 \n(fn (SECONDS TIMEOUT-FORMS...) BODY)"
447 (let ((seconds (car list))
448 (timeout-forms (cdr list)))
449 `(let ((with-timeout-tag (cons nil nil))
450 with-timeout-value with-timeout-timer
451 (with-timeout-timers with-timeout-timers))
452 (if (catch with-timeout-tag
454 (setq with-timeout-timer
455 (run-with-timer ,seconds nil
456 'with-timeout-handler
458 (push with-timeout-timer with-timeout-timers)
459 (setq with-timeout-value (progn . ,body))
461 (progn . ,timeout-forms)
462 (cancel-timer with-timeout-timer)
463 with-timeout-value))))
465 (defun with-timeout-suspend ()
466 "Stop the clock for `with-timeout'. Used by debuggers.
467 The idea is that the time you spend in the debugger should not
468 count against these timeouts.
470 The value is a list that the debugger can pass to `with-timeout-unsuspend'
471 when it exits, to make these timers start counting again."
472 (mapcar (lambda (timer)
476 ;; The time that this timer will go off.
477 (list (aref timer 1) (aref timer 2) (aref timer 3))
479 with-timeout-timers))
481 (defun with-timeout-unsuspend (timer-spec-list)
482 "Restart the clock for `with-timeout'.
483 The argument should be a value previously returned by `with-timeout-suspend'."
484 (dolist (elt timer-spec-list)
485 (let ((timer (car elt))
487 (timer-set-time timer (time-add (current-time) delay))
488 (timer-activate timer))))
490 (defun y-or-n-p-with-timeout (prompt seconds default-value)
491 "Like (y-or-n-p PROMPT), with a timeout.
492 If the user does not answer after SECONDS seconds, return DEFAULT-VALUE."
493 (with-timeout (seconds default-value)
496 (defvar timer-duration-words
497 (list (cons "microsec" 0.000001)
498 (cons "microsecond" 0.000001)
499 (cons "millisec" 0.001)
500 (cons "millisecond" 0.001)
505 (cons "hour" (* 60 60))
506 (cons "day" (* 24 60 60))
507 (cons "week" (* 7 24 60 60))
508 (cons "fortnight" (* 14 24 60 60))
509 (cons "month" (* 30 24 60 60)) ; Approximation
510 (cons "year" (* 365.25 24 60 60)) ; Approximation
512 "Alist mapping temporal words to durations in seconds")
514 (defun timer-duration (string)
515 "Return number of seconds specified by STRING, or nil if parsing fails."
518 (case-fold-search t))
520 "[ \t]*\\([0-9.]+\\)?[ \t]*\\([a-z]+[a-rt-z]\\)s?[ \t]*"
522 (let ((count (if (match-beginning 1)
523 (string-to-number (match-string 1 string))
525 (itemsize (cdr (assoc (match-string 2 string)
526 timer-duration-words))))
528 (setq start (match-end 0)
529 secs (+ secs (* count itemsize)))
531 start (length string)))))
532 (if (= start (length string))
534 (if (string-match "\\`[0-9.]+\\'" string)
535 (string-to-number string)))))
539 ;;; arch-tag: b1a9237b-7787-4382-9e46-8f2c3b3273e0
540 ;;; timer.el ends here