Support higher-resolution time stamps.
[bpt/emacs.git] / lisp / emacs-lisp / timer.el
1 ;;; timer.el --- run a function with args at some time in future
2
3 ;; Copyright (C) 1996, 2001-2012 Free Software Foundation, Inc.
4
5 ;; Maintainer: FSF
6 ;; Package: emacs
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 3 of the License, or
13 ;; (at your option) 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. If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
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.
27
28 ;;; Code:
29
30 ;; Layout of a timer vector:
31 ;; [triggered-p high-seconds low-seconds usecs psecs repeat-delay
32 ;; function args idle-delay]
33 ;; triggered-p is nil if the timer is active (waiting to be triggered),
34 ;; t if it is inactive ("already triggered", in theory)
35
36 (eval-when-compile (require 'cl-lib))
37
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 psecs repeat-delay function args idle-delay)
46
47 (defun timerp (object)
48 "Return t if OBJECT is a timer."
49 (and (vectorp object) (= (length object) 9)))
50
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)))
57
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))))
74
75
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)
84
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)
97
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)))))
120
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)))
131
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)))
135
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)))
142
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 (setf (timer--time timer) time)
150 (setf (timer--usecs timer) usecs)
151 (setf (timer--psecs timer) 0)
152 (setf (timer--repeat-delay timer) (and (numberp delta) (> delta 0) delta))
153 timer)
154 (make-obsolete 'timer-set-time-with-usecs
155 "use `timer-set-time' and `timer-inc-time' instead."
156 "22.1")
157
158 (defun timer-set-function (timer function &optional args)
159 "Make TIMER call FUNCTION with optional ARGS when triggering."
160 (or (timerp timer)
161 (error "Invalid timer"))
162 (setf (timer--function timer) function)
163 (setf (timer--args timer) args)
164 timer)
165 \f
166 (defun timer--activate (timer &optional triggered-p reuse-cell idle)
167 (if (and (timerp timer)
168 (integerp (timer--high-seconds timer))
169 (integerp (timer--low-seconds timer))
170 (integerp (timer--usecs timer))
171 (integerp (timer--psecs timer))
172 (timer--function timer))
173 (let ((timers (if idle timer-idle-list timer-list))
174 last)
175 ;; Skip all timers to trigger before the new one.
176 (while (and timers (timer--time-less-p (car timers) timer))
177 (setq last timers
178 timers (cdr timers)))
179 (if reuse-cell
180 (progn
181 (setcar reuse-cell timer)
182 (setcdr reuse-cell timers))
183 (setq reuse-cell (cons timer timers)))
184 ;; Insert new timer after last which possibly means in front of queue.
185 (cond (last (setcdr last reuse-cell))
186 (idle (setq timer-idle-list reuse-cell))
187 (t (setq timer-list reuse-cell)))
188 (setf (timer--triggered timer) triggered-p)
189 (setf (timer--idle-delay timer) idle)
190 nil)
191 (error "Invalid or uninitialized timer")))
192
193 (defun timer-activate (timer &optional triggered-p reuse-cell)
194 "Insert TIMER into `timer-list'.
195 If TRIGGERED-P is t, make TIMER inactive (put it on the list, but
196 mark it as already triggered). To remove it, use `cancel-timer'.
197
198 REUSE-CELL, if non-nil, is a cons cell to reuse when inserting
199 TIMER into `timer-list' (usually a cell removed from that list by
200 `cancel-timer-internal'; using this reduces consing for repeat
201 timers). If nil, allocate a new cell."
202 (timer--activate timer triggered-p reuse-cell nil))
203
204 (defun timer-activate-when-idle (timer &optional dont-wait reuse-cell)
205 "Insert TIMER into `timer-idle-list'.
206 This arranges to activate TIMER whenever Emacs is next idle.
207 If optional argument DONT-WAIT is non-nil, set TIMER to activate
208 immediately, or at the right time, if Emacs is already idle.
209
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."
214 (timer--activate timer (not dont-wait) reuse-cell 'idle))
215
216 (defalias 'disable-timeout 'cancel-timer)
217
218 (defun cancel-timer (timer)
219 "Remove TIMER from the list of active timers."
220 (or (timerp timer)
221 (error "Invalid timer"))
222 (setq timer-list (delq timer timer-list))
223 (setq timer-idle-list (delq timer timer-idle-list))
224 nil)
225
226 (defun cancel-timer-internal (timer)
227 "Remove TIMER from the list of active timers or idle timers.
228 Only to be used in this file. It returns the cons cell
229 that was removed from the timer list."
230 (let ((cell1 (memq timer timer-list))
231 (cell2 (memq timer timer-idle-list)))
232 (if cell1
233 (setq timer-list (delq timer timer-list)))
234 (if cell2
235 (setq timer-idle-list (delq timer timer-idle-list)))
236 (or cell1 cell2)))
237
238 (defun cancel-function-timers (function)
239 "Cancel all timers which would run FUNCTION.
240 This affects ordinary timers such as are scheduled by `run-at-time',
241 and idle timers such as are scheduled by `run-with-idle-timer'."
242 (interactive "aCancel timers of function: ")
243 (dolist (timer timer-list)
244 (if (eq (timer--function timer) function)
245 (setq timer-list (delq timer timer-list))))
246 (dolist (timer timer-idle-list)
247 (if (eq (timer--function timer) function)
248 (setq timer-idle-list (delq timer timer-idle-list)))))
249 \f
250 ;; Record the last few events, for debugging.
251 (defvar timer-event-last nil
252 "Last timer that was run.")
253 (defvar timer-event-last-1 nil
254 "Next-to-last timer that was run.")
255 (defvar timer-event-last-2 nil
256 "Third-to-last timer that was run.")
257
258 (defcustom timer-max-repeats 10
259 "Maximum number of times to repeat a timer, if many repeats are delayed.
260 Timer invocations can be delayed because Emacs is suspended or busy,
261 or because the system's time changes. If such an occurrence makes it
262 appear that many invocations are overdue, this variable controls
263 how many will really happen."
264 :type 'integer
265 :group 'internal)
266
267 (defun timer-until (timer time)
268 "Calculate number of seconds from when TIMER will run, until TIME.
269 TIMER is a timer, and stands for the time when its next repeat is scheduled.
270 TIME is a time-list."
271 (float-time (time-subtract time (timer--time timer))))
272
273 (defun timer-event-handler (timer)
274 "Call the handler for the timer TIMER.
275 This function is called, by name, directly by the C code."
276 (setq timer-event-last-2 timer-event-last-1)
277 (setq timer-event-last-1 timer-event-last)
278 (setq timer-event-last timer)
279 (let ((inhibit-quit t))
280 (if (timerp timer)
281 (let (retrigger cell)
282 ;; Delete from queue. Record the cons cell that was used.
283 (setq cell (cancel-timer-internal timer))
284 ;; Re-schedule if requested.
285 (if (timer--repeat-delay timer)
286 (if (timer--idle-delay timer)
287 (timer-activate-when-idle timer nil cell)
288 (timer-inc-time timer (timer--repeat-delay timer) 0)
289 ;; If real time has jumped forward,
290 ;; perhaps because Emacs was suspended for a long time,
291 ;; limit how many times things get repeated.
292 (if (and (numberp timer-max-repeats)
293 (< 0 (timer-until timer (current-time))))
294 (let ((repeats (/ (timer-until timer (current-time))
295 (timer--repeat-delay timer))))
296 (if (> repeats timer-max-repeats)
297 (timer-inc-time timer (* (timer--repeat-delay timer)
298 repeats)))))
299 (timer-activate timer t cell)
300 (setq retrigger t)))
301 ;; Run handler.
302 ;; We do this after rescheduling so that the handler function
303 ;; can cancel its own timer successfully with cancel-timer.
304 (condition-case nil
305 ;; Timer functions should not change the current buffer.
306 ;; If they do, all kinds of nasty surprises can happen,
307 ;; and it can be hellish to track down their source.
308 (save-current-buffer
309 (apply (timer--function timer) (timer--args timer)))
310 (error nil))
311 (if retrigger
312 (setf (timer--triggered timer) nil)))
313 (error "Bogus timer event"))))
314
315 ;; This function is incompatible with the one in levents.el.
316 (defun timeout-event-p (event)
317 "Non-nil if EVENT is a timeout event."
318 (and (listp event) (eq (car event) 'timer-event)))
319 \f
320
321 (declare-function diary-entry-time "diary-lib" (s))
322
323 (defun run-at-time (time repeat function &rest args)
324 "Perform an action at time TIME.
325 Repeat the action every REPEAT seconds, if REPEAT is non-nil.
326 TIME should be one of: a string giving an absolute time like
327 \"11:23pm\" (the acceptable formats are those recognized by
328 `diary-entry-time'; note that such times are interpreted as times
329 today, even if in the past); a string giving a relative time like
330 \"2 hours 35 minutes\" (the acceptable formats are those
331 recognized by `timer-duration'); nil meaning now; a number of
332 seconds from now; a value from `encode-time'; or t (with non-nil
333 REPEAT) meaning the next integral multiple of REPEAT. REPEAT may
334 be an integer or floating point number. The action is to call
335 FUNCTION with arguments ARGS.
336
337 This function returns a timer object which you can use in `cancel-timer'."
338 (interactive "sRun at time: \nNRepeat interval: \naFunction: ")
339
340 (or (null repeat)
341 (and (numberp repeat) (< 0 repeat))
342 (error "Invalid repetition interval"))
343
344 ;; Special case: nil means "now" and is useful when repeating.
345 (if (null time)
346 (setq time (current-time)))
347
348 ;; Special case: t means the next integral multiple of REPEAT.
349 (if (and (eq time t) repeat)
350 (setq time (timer-next-integral-multiple-of-time (current-time) repeat)))
351
352 ;; Handle numbers as relative times in seconds.
353 (if (numberp time)
354 (setq time (timer-relative-time (current-time) time)))
355
356 ;; Handle relative times like "2 hours 35 minutes"
357 (if (stringp time)
358 (let ((secs (timer-duration time)))
359 (if secs
360 (setq time (timer-relative-time (current-time) secs)))))
361
362 ;; Handle "11:23pm" and the like. Interpret it as meaning today
363 ;; which admittedly is rather stupid if we have passed that time
364 ;; already. (Though only Emacs hackers hack Emacs at that time.)
365 (if (stringp time)
366 (progn
367 (require 'diary-lib)
368 (let ((hhmm (diary-entry-time time))
369 (now (decode-time)))
370 (if (>= hhmm 0)
371 (setq time
372 (encode-time 0 (% hhmm 100) (/ hhmm 100) (nth 3 now)
373 (nth 4 now) (nth 5 now) (nth 8 now)))))))
374
375 (or (consp time)
376 (error "Invalid time format"))
377
378 (let ((timer (timer-create)))
379 (timer-set-time timer time repeat)
380 (timer-set-function timer function args)
381 (timer-activate timer)
382 timer))
383
384 (defun run-with-timer (secs repeat function &rest args)
385 "Perform an action after a delay of SECS seconds.
386 Repeat the action every REPEAT seconds, if REPEAT is non-nil.
387 SECS and REPEAT may be integers or floating point numbers.
388 The action is to call FUNCTION with arguments ARGS.
389
390 This function returns a timer object which you can use in `cancel-timer'."
391 (interactive "sRun after delay (seconds): \nNRepeat interval: \naFunction: ")
392 (apply 'run-at-time secs repeat function args))
393
394 (defun add-timeout (secs function object &optional repeat)
395 "Add a timer to run SECS seconds from now, to call FUNCTION on OBJECT.
396 If REPEAT is non-nil, repeat the timer every REPEAT seconds.
397 This function is for compatibility; see also `run-with-timer'."
398 (run-with-timer secs repeat function object))
399
400 (defun run-with-idle-timer (secs repeat function &rest args)
401 "Perform an action the next time Emacs is idle for SECS seconds.
402 The action is to call FUNCTION with arguments ARGS.
403 SECS may be an integer, a floating point number, or the internal
404 time format returned by, e.g., `current-idle-time'.
405 If Emacs is currently idle, and has been idle for N seconds (N < SECS),
406 then it will call FUNCTION in SECS - N seconds from now.
407
408 If REPEAT is non-nil, do the action each time Emacs has been idle for
409 exactly SECS seconds (that is, only once for each time Emacs becomes idle).
410
411 This function returns a timer object which you can use in `cancel-timer'."
412 (interactive
413 (list (read-from-minibuffer "Run after idle (seconds): " nil nil t)
414 (y-or-n-p "Repeat each time Emacs is idle? ")
415 (intern (completing-read "Function: " obarray 'fboundp t))))
416 (let ((timer (timer-create)))
417 (timer-set-function timer function args)
418 (timer-set-idle-time timer secs repeat)
419 (timer-activate-when-idle timer t)
420 timer))
421 \f
422 (defvar with-timeout-timers nil
423 "List of all timers used by currently pending `with-timeout' calls.")
424
425 (defmacro with-timeout (list &rest body)
426 "Run BODY, but if it doesn't finish in SECONDS seconds, give up.
427 If we give up, we run the TIMEOUT-FORMS and return the value of the last one.
428 The timeout is checked whenever Emacs waits for some kind of external
429 event (such as keyboard input, input from subprocesses, or a certain time);
430 if the program loops without waiting in any way, the timeout will not
431 be detected.
432 \n(fn (SECONDS TIMEOUT-FORMS...) BODY)"
433 (declare (indent 1) (debug ((form body) body)))
434 (let ((seconds (car list))
435 (timeout-forms (cdr list))
436 (timeout (make-symbol "timeout")))
437 `(let ((-with-timeout-value-
438 (catch ',timeout
439 (let* ((-with-timeout-timer-
440 (run-with-timer ,seconds nil
441 (lambda () (throw ',timeout ',timeout))))
442 (with-timeout-timers
443 (cons -with-timeout-timer- with-timeout-timers)))
444 (unwind-protect
445 ,@body
446 (cancel-timer -with-timeout-timer-))))))
447 ;; It is tempting to avoid the `if' altogether and instead run
448 ;; timeout-forms in the timer, just before throwing `timeout'.
449 ;; But that would mean that timeout-forms are run in the deeper
450 ;; dynamic context of the timer, with inhibit-quit set etc...
451 (if (eq -with-timeout-value- ',timeout)
452 (progn ,@timeout-forms)
453 -with-timeout-value-))))
454
455 (defun with-timeout-suspend ()
456 "Stop the clock for `with-timeout'. Used by debuggers.
457 The idea is that the time you spend in the debugger should not
458 count against these timeouts.
459
460 The value is a list that the debugger can pass to `with-timeout-unsuspend'
461 when it exits, to make these timers start counting again."
462 (mapcar (lambda (timer)
463 (cancel-timer timer)
464 (list timer (time-subtract (timer--time timer) (current-time))))
465 with-timeout-timers))
466
467 (defun with-timeout-unsuspend (timer-spec-list)
468 "Restart the clock for `with-timeout'.
469 The argument should be a value previously returned by `with-timeout-suspend'."
470 (dolist (elt timer-spec-list)
471 (let ((timer (car elt))
472 (delay (cadr elt)))
473 (timer-set-time timer (time-add (current-time) delay))
474 (timer-activate timer))))
475
476 (defun y-or-n-p-with-timeout (prompt seconds default-value)
477 "Like (y-or-n-p PROMPT), with a timeout.
478 If the user does not answer after SECONDS seconds, return DEFAULT-VALUE."
479 (with-timeout (seconds default-value)
480 (y-or-n-p prompt)))
481 \f
482 (defconst timer-duration-words
483 (list (cons "microsec" 0.000001)
484 (cons "microsecond" 0.000001)
485 (cons "millisec" 0.001)
486 (cons "millisecond" 0.001)
487 (cons "sec" 1)
488 (cons "second" 1)
489 (cons "min" 60)
490 (cons "minute" 60)
491 (cons "hour" (* 60 60))
492 (cons "day" (* 24 60 60))
493 (cons "week" (* 7 24 60 60))
494 (cons "fortnight" (* 14 24 60 60))
495 (cons "month" (* 30 24 60 60)) ; Approximation
496 (cons "year" (* 365.25 24 60 60)) ; Approximation
497 )
498 "Alist mapping temporal words to durations in seconds.")
499
500 (defun timer-duration (string)
501 "Return number of seconds specified by STRING, or nil if parsing fails."
502 (let ((secs 0)
503 (start 0)
504 (case-fold-search t))
505 (while (string-match
506 "[ \t]*\\([0-9.]+\\)?[ \t]*\\([a-z]+[a-rt-z]\\)s?[ \t]*"
507 string start)
508 (let ((count (if (match-beginning 1)
509 (string-to-number (match-string 1 string))
510 1))
511 (itemsize (cdr (assoc (match-string 2 string)
512 timer-duration-words))))
513 (if itemsize
514 (setq start (match-end 0)
515 secs (+ secs (* count itemsize)))
516 (setq secs nil
517 start (length string)))))
518 (if (= start (length string))
519 secs
520 (if (string-match-p "\\`[0-9.]+\\'" string)
521 (string-to-number string)))))
522 \f
523 (provide 'timer)
524
525 ;;; timer.el ends here