]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/timer.el
Merged from emacs@sv.gnu.org
[gnu-emacs] / lisp / emacs-lisp / timer.el
1 ;;; timer.el --- run a function with args at some time in future
2
3 ;; Copyright (C) 1996, 2002, 2003, 2004, 2005,
4 ;; 2006 Free Software Foundation, Inc.
5
6 ;; Maintainer: FSF
7
8 ;; This file is part of GNU Emacs.
9
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)
13 ;; any later version.
14
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.
19
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.
24
25 ;;; Commentary:
26
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.
29
30 ;;; Code:
31
32 ;; Layout of a timer vector:
33 ;; [triggered-p high-seconds low-seconds usecs repeat-delay
34 ;; function args idle-delay]
35
36 (defun timer-create ()
37 "Create a timer object."
38 (let ((timer (make-vector 8 nil)))
39 (aset timer 0 t)
40 timer))
41
42 (defun timerp (object)
43 "Return t if OBJECT is a timer."
44 (and (vectorp object) (= (length object) 8)))
45
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."
51 (or (timerp timer)
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)))
56 (nth 2 time))
57 0))
58 (aset timer 4 (and (numberp delta) (> delta 0) delta))
59 timer)
60
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."
67 (or (timerp timer)
68 (error "Invalid timer"))
69 (if (consp secs)
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)))
73 (nth 2 secs))
74 0)))
75 (aset timer 1 0)
76 (aset timer 2 0)
77 (aset timer 3 0)
78 (timer-inc-time timer secs))
79 (aset timer 4 repeat)
80 timer)
81
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)))
87 (if (fboundp 'atan)
88 ;; Use floating point, taking care to not lose precision.
89 (let* ((float-time-base (float time-base))
90 (million 1000000.0)
91 (time-usec (+ (* million
92 (+ (* float-time-base (nth 0 time))
93 (nth 1 time)))
94 (nth 2 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))
106 (nth 1 time))
107 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)
111 0)))))
112
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))))
119 (nth 2 time)
120 0)))
121 ;; Add
122 (if usecs (setq micro (+ micro usecs)))
123 (if (floatp secs)
124 (setq micro (+ micro (floor (* 1000000 (- secs (floor secs)))))))
125 (setq low (+ low (floor secs)))
126
127 ;; Normalize
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))
134
135 (list high low (and (/= micro 0) micro))))
136
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))
142 secs
143 usecs)))
144 (aset timer 1 (nth 0 time))
145 (aset timer 2 (nth 1 time))
146 (aset timer 3 (or (nth 2 time) 0))))
147
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."
154 (or (timerp timer)
155 (error "Invalid timer"))
156 (aset timer 1 (nth 0 time))
157 (aset timer 2 (nth 1 time))
158 (aset timer 3 usecs)
159 (aset timer 4 (and (numberp delta) (> delta 0) delta))
160 timer)
161 (make-obsolete 'timer-set-time-with-usecs
162 "use `timer-set-time' and `timer-inc-time' instead."
163 "22.1")
164
165 (defun timer-set-function (timer function &optional args)
166 "Make TIMER call FUNCTION with optional ARGS when triggering."
167 (or (timerp timer)
168 (error "Invalid timer"))
169 (aset timer 5 function)
170 (aset timer 6 args)
171 timer)
172 \f
173 (defun timer-activate (timer &optional triggered-p reuse-cell)
174 "Put TIMER on the list of active timers.
175
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))
182 (aref timer 5))
183 (let ((timers timer-list)
184 last)
185 ;; Skip all timers to trigger before the new one.
186 (while (and timers
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)))))
193 (setq last timers
194 timers (cdr timers)))
195 (if reuse-cell
196 (progn
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.
201 (if last
202 (setcdr last reuse-cell)
203 (setq timer-list reuse-cell))
204 (aset timer 0 triggered-p)
205 (aset timer 7 nil)
206 nil)
207 (error "Invalid or uninitialized timer")))
208
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
213 is already idle.
214
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))
221 (aref timer 5))
222 (let ((timers timer-idle-list)
223 last)
224 ;; Skip all timers to trigger before the new one.
225 (while (and timers
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)))))
232 (setq last timers
233 timers (cdr timers)))
234 (if reuse-cell
235 (progn
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.
240 (if last
241 (setcdr last reuse-cell)
242 (setq timer-idle-list reuse-cell))
243 (aset timer 0 (not dont-wait))
244 (aset timer 7 t)
245 nil)
246 (error "Invalid or uninitialized timer")))
247
248 ;;;###autoload
249 (defalias 'disable-timeout 'cancel-timer)
250 ;;;###autoload
251 (defun cancel-timer (timer)
252 "Remove TIMER from the list of active timers."
253 (or (timerp timer)
254 (error "Invalid timer"))
255 (setq timer-list (delq timer timer-list))
256 (setq timer-idle-list (delq timer timer-idle-list))
257 nil)
258
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)))
265 (if cell1
266 (setq timer-list (delq timer timer-list)))
267 (if cell2
268 (setq timer-idle-list (delq timer timer-idle-list)))
269 (or cell1 cell2)))
270
271 ;;;###autoload
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))
276 (while tail
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))
281 (while tail
282 (if (eq (aref (car tail) 5) function)
283 (setq timer-idle-list (delq (car tail) timer-idle-list)))
284 (setq tail (cdr tail)))))
285 \f
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)
290
291 (defvar timer-max-repeats 10
292 "*Maximum number of times to repeat a timer, if real time jumps.")
293
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))))
301
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))
309 (if (timerp timer)
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.
314 (if (aref timer 4)
315 (if (aref timer 7)
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))
324 (aref timer 4))))
325 (if (> repeats timer-max-repeats)
326 (timer-inc-time timer (* (aref timer 4) repeats)))))
327 (timer-activate timer t cell)
328 (setq retrigger t)))
329 ;; Run handler.
330 ;; We do this after rescheduling so that the handler function
331 ;; can cancel its own timer successfully with cancel-timer.
332 (condition-case nil
333 (apply (aref timer 5) (aref timer 6))
334 (error nil))
335 (if retrigger
336 (aset timer 0 nil)))
337 (error "Bogus timer event"))))
338
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)))
343 \f
344 ;;;###autoload
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.
353
354 This function returns a timer object which you can use in `cancel-timer'."
355 (interactive "sRun at time: \nNRepeat interval: \naFunction: ")
356
357 (or (null repeat)
358 (and (numberp repeat) (< 0 repeat))
359 (error "Invalid repetition interval"))
360
361 ;; Special case: nil means "now" and is useful when repeating.
362 (if (null time)
363 (setq time (current-time)))
364
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)))
368
369 ;; Handle numbers as relative times in seconds.
370 (if (numberp time)
371 (setq time (timer-relative-time (current-time) time)))
372
373 ;; Handle relative times like "2 hours and 35 minutes"
374 (if (stringp time)
375 (let ((secs (timer-duration time)))
376 (if secs
377 (setq time (timer-relative-time (current-time) secs)))))
378
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.)
382 (if (stringp time)
383 (progn
384 (require 'diary-lib)
385 (let ((hhmm (diary-entry-time time))
386 (now (decode-time)))
387 (if (>= hhmm 0)
388 (setq time
389 (encode-time 0 (% hhmm 100) (/ hhmm 100) (nth 3 now)
390 (nth 4 now) (nth 5 now) (nth 8 now)))))))
391
392 (or (consp time)
393 (error "Invalid time format"))
394
395 (let ((timer (timer-create)))
396 (timer-set-time timer time repeat)
397 (timer-set-function timer function args)
398 (timer-activate timer)
399 timer))
400
401 ;;;###autoload
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.
407
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))
411
412 ;;;###autoload
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))
418
419 ;;;###autoload
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.
427
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).
430
431 This function returns a timer object which you can use in `cancel-timer'."
432 (interactive
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)
440 timer))
441 \f
442 (defun with-timeout-handler (tag)
443 (throw tag 'timeout))
444
445 ;;;###autoload (put 'with-timeout 'lisp-indent-function 1)
446
447 (defvar with-timeout-timers nil
448 "List of all timers used by currently pending `with-timeout' calls.")
449
450 ;;;###autoload
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
457 be detected.
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
465 (progn
466 (setq with-timeout-timer
467 (run-with-timer ,seconds nil
468 'with-timeout-handler
469 with-timeout-tag))
470 (push with-timeout-timer with-timeout-timers)
471 (setq with-timeout-value (progn . ,body))
472 nil))
473 (progn . ,timeout-forms)
474 (cancel-timer with-timeout-timer)
475 with-timeout-value))))
476
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.
481
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)
485 (cancel-timer timer)
486 (list timer
487 (time-subtract
488 ;; The time that this timer will go off.
489 (list (aref timer 1) (aref timer 2) (aref timer 3))
490 (current-time))))
491 with-timeout-timers))
492
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))
498 (delay (cadr elt)))
499 (timer-set-time timer (time-add (current-time) delay))
500 (timer-activate timer))))
501
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)
506 (y-or-n-p prompt)))
507 \f
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)
513 (cons "sec" 1)
514 (cons "second" 1)
515 (cons "min" 60)
516 (cons "minute" 60)
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
523 )
524 "Alist mapping temporal words to durations in seconds")
525
526 (defun timer-duration (string)
527 "Return number of seconds specified by STRING, or nil if parsing fails."
528 (let ((secs 0)
529 (start 0)
530 (case-fold-search t))
531 (while (string-match
532 "[ \t]*\\([0-9.]+\\)?[ \t]*\\([a-z]+[a-rt-z]\\)s?[ \t]*"
533 string start)
534 (let ((count (if (match-beginning 1)
535 (string-to-number (match-string 1 string))
536 1))
537 (itemsize (cdr (assoc (match-string 2 string)
538 timer-duration-words))))
539 (if itemsize
540 (setq start (match-end 0)
541 secs (+ secs (* count itemsize)))
542 (setq secs nil
543 start (length string)))))
544 (if (= start (length string))
545 secs
546 (if (string-match "\\`[0-9.]+\\'" string)
547 (string-to-number string)))))
548 \f
549 (provide 'timer)
550
551 ;;; arch-tag: b1a9237b-7787-4382-9e46-8f2c3b3273e0
552 ;;; timer.el ends here