]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/timer.el
*** empty log message ***
[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 Free Software Foundation, Inc.
4
5 ;; Maintainer: FSF
6
7 ;; This file is part of GNU Emacs.
8
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)
12 ;; any later version.
13
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.
18
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.
23
24 ;;; Commentary:
25
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.
28
29 ;;; Code:
30
31 ;; Layout of a timer vector:
32 ;; [triggered-p high-seconds low-seconds usecs repeat-delay
33 ;; function args idle-delay]
34
35 (defun timer-create ()
36 "Create a timer object."
37 (let ((timer (make-vector 8 nil)))
38 (aset timer 0 t)
39 timer))
40
41 (defun timerp (object)
42 "Return t if OBJECT is a timer."
43 (and (vectorp object) (= (length object) 8)))
44
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."
50 (or (timerp timer)
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)))
55 (nth 2 time))
56 0))
57 (aset timer 4 (and (numberp delta) (> delta 0) delta))
58 timer)
59
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."
64 (or (timerp timer)
65 (error "Invalid timer"))
66 (aset timer 1 0)
67 (aset timer 2 0)
68 (aset timer 3 0)
69 (timer-inc-time timer secs)
70 (aset timer 4 repeat)
71 timer)
72
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)))
78 (if (fboundp 'atan)
79 ;; Use floating point, taking care to not lose precision.
80 (let* ((float-time-base (float time-base))
81 (million 1000000.0)
82 (time-usec (+ (* million
83 (+ (* float-time-base (nth 0 time))
84 (nth 1 time)))
85 (nth 2 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))
97 (nth 1 time))
98 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)
102 0)))))
103
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))))
110 (nth 2 time)
111 0)))
112 ;; Add
113 (if usecs (setq micro (+ micro usecs)))
114 (if (floatp secs)
115 (setq micro (+ micro (floor (* 1000000 (- secs (floor secs)))))))
116 (setq low (+ low (floor secs)))
117
118 ;; Normalize
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))
125
126 (list high low (and (/= micro 0) micro))))
127
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))
133 secs
134 usecs)))
135 (aset timer 1 (nth 0 time))
136 (aset timer 2 (nth 1 time))
137 (aset timer 3 (or (nth 2 time) 0))))
138
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."
145 (or (timerp timer)
146 (error "Invalid timer"))
147 (aset timer 1 (nth 0 time))
148 (aset timer 2 (nth 1 time))
149 (aset timer 3 usecs)
150 (aset timer 4 (and (numberp delta) (> delta 0) delta))
151 timer)
152 (make-obsolete 'timer-set-time-with-usecs
153 "use `timer-set-time' and `timer-inc-time' instead."
154 "22.1")
155
156 (defun timer-set-function (timer function &optional args)
157 "Make TIMER call FUNCTION with optional ARGS when triggering."
158 (or (timerp timer)
159 (error "Invalid timer"))
160 (aset timer 5 function)
161 (aset timer 6 args)
162 timer)
163 \f
164 (defun timer-activate (timer &optional triggered-p reuse-cell)
165 "Put TIMER on the list of active timers.
166
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))
173 (aref timer 5))
174 (let ((timers timer-list)
175 last)
176 ;; Skip all timers to trigger before the new one.
177 (while (and timers
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)))))
184 (setq last timers
185 timers (cdr timers)))
186 (if reuse-cell
187 (progn
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.
192 (if last
193 (setcdr last reuse-cell)
194 (setq timer-list reuse-cell))
195 (aset timer 0 triggered-p)
196 (aset timer 7 nil)
197 nil)
198 (error "Invalid or uninitialized timer")))
199
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
204 is already idle.
205
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))
212 (aref timer 5))
213 (let ((timers timer-idle-list)
214 last)
215 ;; Skip all timers to trigger before the new one.
216 (while (and timers
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)))))
223 (setq last timers
224 timers (cdr timers)))
225 (if reuse-cell
226 (progn
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.
231 (if last
232 (setcdr last reuse-cell)
233 (setq timer-idle-list reuse-cell))
234 (aset timer 0 (not dont-wait))
235 (aset timer 7 t)
236 nil)
237 (error "Invalid or uninitialized timer")))
238
239 ;;;###autoload
240 (defalias 'disable-timeout 'cancel-timer)
241 ;;;###autoload
242 (defun cancel-timer (timer)
243 "Remove TIMER from the list of active timers."
244 (or (timerp timer)
245 (error "Invalid timer"))
246 (setq timer-list (delq timer timer-list))
247 (setq timer-idle-list (delq timer timer-idle-list))
248 nil)
249
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)))
256 (if cell1
257 (setq timer-list (delq timer timer-list)))
258 (if cell2
259 (setq timer-idle-list (delq timer timer-idle-list)))
260 (or cell1 cell2)))
261
262 ;;;###autoload
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))
267 (while tail
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))
272 (while tail
273 (if (eq (aref (car tail) 5) function)
274 (setq timer-idle-list (delq (car tail) timer-idle-list)))
275 (setq tail (cdr tail)))))
276 \f
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)
281
282 (defvar timer-max-repeats 10
283 "*Maximum number of times to repeat a timer, if real time jumps.")
284
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))))
292
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))
300 (if (timerp timer)
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.
305 (if (aref timer 4)
306 (if (aref timer 7)
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))
315 (aref timer 4))))
316 (if (> repeats timer-max-repeats)
317 (timer-inc-time timer (* (aref timer 4) repeats)))))
318 (timer-activate timer t cell)
319 (setq retrigger t)))
320 ;; Run handler.
321 ;; We do this after rescheduling so that the handler function
322 ;; can cancel its own timer successfully with cancel-timer.
323 (condition-case nil
324 (apply (aref timer 5) (aref timer 6))
325 (error nil))
326 (if retrigger
327 (aset timer 0 nil)))
328 (error "Bogus timer event"))))
329
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)))
334 \f
335 ;;;###autoload
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.
344
345 This function returns a timer object which you can use in `cancel-timer'."
346 (interactive "sRun at time: \nNRepeat interval: \naFunction: ")
347
348 (or (null repeat)
349 (and (numberp repeat) (< 0 repeat))
350 (error "Invalid repetition interval"))
351
352 ;; Special case: nil means "now" and is useful when repeating.
353 (if (null time)
354 (setq time (current-time)))
355
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)))
359
360 ;; Handle numbers as relative times in seconds.
361 (if (numberp time)
362 (setq time (timer-relative-time (current-time) time)))
363
364 ;; Handle relative times like "2 hours and 35 minutes"
365 (if (stringp time)
366 (let ((secs (timer-duration time)))
367 (if secs
368 (setq time (timer-relative-time (current-time) secs)))))
369
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.)
373 (if (stringp time)
374 (progn
375 (require 'diary-lib)
376 (let ((hhmm (diary-entry-time time))
377 (now (decode-time)))
378 (if (>= hhmm 0)
379 (setq time
380 (encode-time 0 (% hhmm 100) (/ hhmm 100) (nth 3 now)
381 (nth 4 now) (nth 5 now) (nth 8 now)))))))
382
383 (or (consp time)
384 (error "Invalid time format"))
385
386 (let ((timer (timer-create)))
387 (timer-set-time timer time repeat)
388 (timer-set-function timer function args)
389 (timer-activate timer)
390 timer))
391
392 ;;;###autoload
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.
398
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))
402
403 ;;;###autoload
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))
409
410 ;;;###autoload
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.
415
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).
418
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)
428 timer))
429 \f
430 (defun with-timeout-handler (tag)
431 (throw tag 'timeout))
432
433 ;;;###autoload (put 'with-timeout 'lisp-indent-function 1)
434
435 (defvar with-timeout-timers nil
436 "List of all timers used by currently pending `with-timeout' calls.")
437
438 ;;;###autoload
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
445 be detected.
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
453 (progn
454 (setq with-timeout-timer
455 (run-with-timer ,seconds nil
456 'with-timeout-handler
457 with-timeout-tag))
458 (push with-timeout-timer with-timeout-timers)
459 (setq with-timeout-value (progn . ,body))
460 nil))
461 (progn . ,timeout-forms)
462 (cancel-timer with-timeout-timer)
463 with-timeout-value))))
464
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.
469
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)
473 (cancel-timer timer)
474 (list timer
475 (time-subtract
476 ;; The time that this timer will go off.
477 (list (aref timer 1) (aref timer 2) (aref timer 3))
478 (current-time))))
479 with-timeout-timers))
480
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))
486 (delay (cadr elt)))
487 (timer-set-time timer (time-add (current-time) delay))
488 (timer-activate timer))))
489
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)
494 (y-or-n-p prompt)))
495 \f
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)
501 (cons "sec" 1)
502 (cons "second" 1)
503 (cons "min" 60)
504 (cons "minute" 60)
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
511 )
512 "Alist mapping temporal words to durations in seconds")
513
514 (defun timer-duration (string)
515 "Return number of seconds specified by STRING, or nil if parsing fails."
516 (let ((secs 0)
517 (start 0)
518 (case-fold-search t))
519 (while (string-match
520 "[ \t]*\\([0-9.]+\\)?[ \t]*\\([a-z]+[a-rt-z]\\)s?[ \t]*"
521 string start)
522 (let ((count (if (match-beginning 1)
523 (string-to-number (match-string 1 string))
524 1))
525 (itemsize (cdr (assoc (match-string 2 string)
526 timer-duration-words))))
527 (if itemsize
528 (setq start (match-end 0)
529 secs (+ secs (* count itemsize)))
530 (setq secs nil
531 start (length string)))))
532 (if (= start (length string))
533 secs
534 (if (string-match "\\`[0-9.]+\\'" string)
535 (string-to-number string)))))
536 \f
537 (provide 'timer)
538
539 ;;; arch-tag: b1a9237b-7787-4382-9e46-8f2c3b3273e0
540 ;;; timer.el ends here