]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/timer.el
* src/keyboard.c (timer_start_idle): Call internal-timer-start-idle instead
[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, 2001-2013 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 (eval-when-compile (require 'cl-lib))
31
32 (cl-defstruct (timer
33 (:constructor nil)
34 (:copier nil)
35 (:constructor timer-create ())
36 (:type vector)
37 (:conc-name timer--))
38 ;; nil if the timer is active (waiting to be triggered),
39 ;; non-nil if it is inactive ("already triggered", in theory).
40 (triggered t)
41 ;; Time of next trigger: for normal timers, absolute time, for idle timers,
42 ;; time relative to idle-start.
43 high-seconds low-seconds usecs
44 ;; For normal timers, time between repetitions, or nil. For idle timers,
45 ;; non-nil iff repeated.
46 repeat-delay
47 function args ;What to do when triggered.
48 idle-delay ;If non-nil, this is an idle-timer.
49 psecs)
50
51 (defun timerp (object)
52 "Return t if OBJECT is a timer."
53 (and (vectorp object) (= (length object) 9)))
54
55 (defsubst timer--check (timer)
56 (or (timerp timer) (signal 'wrong-type-argument (list #'timerp timer))))
57
58 ;; Pseudo field `time'.
59 (defun timer--time (timer)
60 (list (timer--high-seconds timer)
61 (timer--low-seconds timer)
62 (timer--usecs timer)
63 (timer--psecs timer)))
64
65 (gv-define-simple-setter timer--time
66 (lambda (timer time)
67 (timer--check timer)
68 (setf (timer--high-seconds timer) (pop time))
69 (let ((low time) (usecs 0) (psecs 0))
70 (if (consp time)
71 (progn
72 (setq low (pop time))
73 (if time
74 (progn
75 (setq usecs (pop time))
76 (if time
77 (setq psecs (car time)))))))
78 (setf (timer--low-seconds timer) low)
79 (setf (timer--usecs timer) usecs)
80 (setf (timer--psecs timer) psecs))))
81
82
83 (defun timer-set-time (timer time &optional delta)
84 "Set the trigger time of TIMER to TIME.
85 TIME must be in the internal format returned by, e.g., `current-time'.
86 If optional third argument DELTA is a positive number, make the timer
87 fire repeatedly that many seconds apart."
88 (setf (timer--time timer) time)
89 (setf (timer--repeat-delay timer) (and (numberp delta) (> delta 0) delta))
90 timer)
91
92 (defun timer-set-idle-time (timer secs &optional repeat)
93 ;; FIXME: Merge with timer-set-time.
94 "Set the trigger idle time of TIMER to SECS.
95 SECS may be an integer, floating point number, or the internal
96 time format returned by, e.g., `current-idle-time'.
97 If optional third argument REPEAT is non-nil, make the timer
98 fire each time Emacs is idle for that many seconds."
99 (setf (timer--time timer) (if (consp secs) secs (seconds-to-time secs)))
100 (setf (timer--repeat-delay timer) repeat)
101 timer)
102
103 (defun timer-next-integral-multiple-of-time (time secs)
104 "Yield the next value after TIME that is an integral multiple of SECS.
105 More precisely, the next value, after TIME, that is an integral multiple
106 of SECS seconds since the epoch. SECS may be a fraction."
107 (let* ((trillion 1e12)
108 (time-sec (+ (nth 1 time)
109 (* 65536.0 (nth 0 time))))
110 (delta-sec (mod (- time-sec) secs))
111 (next-sec (+ time-sec (ffloor delta-sec)))
112 (next-sec-psec (ffloor (* trillion (mod delta-sec 1))))
113 (sub-time-psec (+ (or (nth 3 time) 0)
114 (* 1e6 (nth 2 time))))
115 (psec-diff (- sub-time-psec next-sec-psec)))
116 (if (and (<= next-sec time-sec) (< 0 psec-diff))
117 (setq next-sec-psec (+ sub-time-psec
118 (mod (- psec-diff) (* trillion secs)))))
119 (setq next-sec (+ next-sec (floor next-sec-psec trillion)))
120 (setq next-sec-psec (mod next-sec-psec trillion))
121 (list (floor next-sec 65536)
122 (floor (mod next-sec 65536))
123 (floor next-sec-psec 1000000)
124 (floor (mod next-sec-psec 1000000)))))
125
126 (defun timer-relative-time (time secs &optional usecs psecs)
127 "Advance TIME by SECS seconds and optionally USECS nanoseconds
128 and PSECS picoseconds. SECS may be either an integer or a
129 floating point number."
130 (let ((delta (if (floatp secs)
131 (seconds-to-time secs)
132 (list (floor secs 65536) (mod secs 65536)))))
133 (if (or usecs psecs)
134 (setq delta (time-add delta (list 0 0 (or usecs 0) (or psecs 0)))))
135 (time-add time delta)))
136
137 (defun timer--time-less-p (t1 t2)
138 "Say whether time value T1 is less than time value T2."
139 (time-less-p (timer--time t1) (timer--time t2)))
140
141 (defun timer-inc-time (timer secs &optional usecs psecs)
142 "Increment the time set in TIMER by SECS seconds, USECS nanoseconds,
143 and PSECS picoseconds. SECS may be a fraction. If USECS or PSECS are
144 omitted, they are treated as zero."
145 (setf (timer--time timer)
146 (timer-relative-time (timer--time timer) secs usecs psecs)))
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 (declare (obsolete "use `timer-set-time' and `timer-inc-time' instead."
155 "22.1"))
156 (setf (timer--time timer) time)
157 (setf (timer--usecs timer) usecs)
158 (setf (timer--psecs timer) 0)
159 (setf (timer--repeat-delay timer) (and (numberp delta) (> delta 0) delta))
160 timer)
161
162 (defun timer-set-function (timer function &optional args)
163 "Make TIMER call FUNCTION with optional ARGS when triggering."
164 (timer--check timer)
165 (setf (timer--function timer) function)
166 (setf (timer--args timer) args)
167 timer)
168 \f
169 (defun timer--activate (timer &optional triggered-p reuse-cell idle)
170 (if (and (timerp timer)
171 (integerp (timer--high-seconds timer))
172 (integerp (timer--low-seconds timer))
173 (integerp (timer--usecs timer))
174 (integerp (timer--psecs timer))
175 (timer--function timer))
176 (let ((timers (if idle timer-idle-list timer-list))
177 last)
178 ;; Skip all timers to trigger before the new one.
179 (while (and timers (timer--time-less-p (car timers) timer))
180 (setq last timers
181 timers (cdr timers)))
182 (if reuse-cell
183 (progn
184 (setcar reuse-cell timer)
185 (setcdr reuse-cell timers))
186 (setq reuse-cell (cons timer timers)))
187 ;; Insert new timer after last which possibly means in front of queue.
188 (setf (cond (last (cdr last))
189 (idle timer-idle-list)
190 (t timer-list))
191 reuse-cell)
192 (setf (timer--triggered timer) triggered-p)
193 (setf (timer--idle-delay timer) idle)
194 nil)
195 (error "Invalid or uninitialized timer")))
196
197 (defun timer-activate (timer &optional triggered-p reuse-cell)
198 "Insert TIMER into `timer-list'.
199 If TRIGGERED-P is t, make TIMER inactive (put it on the list, but
200 mark it as already triggered). To remove it, use `cancel-timer'.
201
202 REUSE-CELL, if non-nil, is a cons cell to reuse when inserting
203 TIMER into `timer-list' (usually a cell removed from that list by
204 `cancel-timer-internal'; using this reduces consing for repeat
205 timers). If nil, allocate a new cell."
206 (timer--activate timer triggered-p reuse-cell nil))
207
208 (defun timer-activate-when-idle (timer &optional dont-wait reuse-cell)
209 "Insert TIMER into `timer-idle-list'.
210 This arranges to activate TIMER whenever Emacs is next idle.
211 If optional argument DONT-WAIT is non-nil, set TIMER to activate
212 immediately \(see below\), or at the right time, if Emacs is
213 already idle.
214
215 REUSE-CELL, if non-nil, is a cons cell to reuse when inserting
216 TIMER into `timer-idle-list' (usually a cell removed from that
217 list by `cancel-timer-internal'; using this reduces consing for
218 repeat timers). If nil, allocate a new cell.
219
220 Using non-nil DONT-WAIT is not recommended when activating an
221 idle timer from an idle timer handler, if the timer being
222 activated has an idleness time that is smaller or equal to
223 the time of the current timer. That's because the activated
224 timer will fire right away."
225 (timer--activate timer (not dont-wait) reuse-cell 'idle))
226
227 (defalias 'disable-timeout 'cancel-timer)
228
229 (defun cancel-timer (timer)
230 "Remove TIMER from the list of active timers."
231 (timer--check timer)
232 (setq timer-list (delq timer timer-list))
233 (setq timer-idle-list (delq timer timer-idle-list))
234 nil)
235
236 (defun cancel-timer-internal (timer)
237 "Remove TIMER from the list of active timers or idle timers.
238 Only to be used in this file. It returns the cons cell
239 that was removed from the timer list."
240 (let ((cell1 (memq timer timer-list))
241 (cell2 (memq timer timer-idle-list)))
242 (if cell1
243 (setq timer-list (delq timer timer-list)))
244 (if cell2
245 (setq timer-idle-list (delq timer timer-idle-list)))
246 (or cell1 cell2)))
247
248 (defun cancel-function-timers (function)
249 "Cancel all timers which would run FUNCTION.
250 This affects ordinary timers such as are scheduled by `run-at-time',
251 and idle timers such as are scheduled by `run-with-idle-timer'."
252 (interactive "aCancel timers of function: ")
253 (dolist (timer timer-list)
254 (if (eq (timer--function timer) function)
255 (setq timer-list (delq timer timer-list))))
256 (dolist (timer timer-idle-list)
257 (if (eq (timer--function timer) function)
258 (setq timer-idle-list (delq timer timer-idle-list)))))
259 \f
260 ;; Record the last few events, for debugging.
261 (defvar timer-event-last nil
262 "Last timer that was run.")
263 (defvar timer-event-last-1 nil
264 "Next-to-last timer that was run.")
265 (defvar timer-event-last-2 nil
266 "Third-to-last timer that was run.")
267
268 (defcustom timer-max-repeats 10
269 "Maximum number of times to repeat a timer, if many repeats are delayed.
270 Timer invocations can be delayed because Emacs is suspended or busy,
271 or because the system's time changes. If such an occurrence makes it
272 appear that many invocations are overdue, this variable controls
273 how many will really happen."
274 :type 'integer
275 :group 'internal)
276
277 (defun timer-until (timer time)
278 "Calculate number of seconds from when TIMER will run, until TIME.
279 TIMER is a timer, and stands for the time when its next repeat is scheduled.
280 TIME is a time-list."
281 (- (float-time time) (float-time (timer--time timer))))
282
283 (defun timer-event-handler (timer)
284 "Call the handler for the timer TIMER.
285 This function is called, by name, directly by the C code."
286 (setq timer-event-last-2 timer-event-last-1)
287 (setq timer-event-last-1 timer-event-last)
288 (setq timer-event-last timer)
289 (let ((inhibit-quit t))
290 (timer--check timer)
291 (let ((retrigger nil)
292 (cell
293 ;; Delete from queue. Record the cons cell that was used.
294 (cancel-timer-internal timer)))
295 ;; Re-schedule if requested.
296 (if (timer--repeat-delay timer)
297 (if (timer--idle-delay timer)
298 (timer-activate-when-idle timer nil cell)
299 (timer-inc-time timer (timer--repeat-delay timer) 0)
300 ;; If real time has jumped forward,
301 ;; perhaps because Emacs was suspended for a long time,
302 ;; limit how many times things get repeated.
303 (if (and (numberp timer-max-repeats)
304 (< 0 (timer-until timer (current-time))))
305 (let ((repeats (/ (timer-until timer (current-time))
306 (timer--repeat-delay timer))))
307 (if (> repeats timer-max-repeats)
308 (timer-inc-time timer (* (timer--repeat-delay timer)
309 repeats)))))
310 ;; Place it back on the timer-list before running
311 ;; timer--function, so it can cancel-timer itself.
312 (timer-activate timer t cell)
313 (setq retrigger t)))
314 ;; Run handler.
315 (condition-case-unless-debug err
316 ;; Timer functions should not change the current buffer.
317 ;; If they do, all kinds of nasty surprises can happen,
318 ;; and it can be hellish to track down their source.
319 (save-current-buffer
320 (apply (timer--function timer) (timer--args timer)))
321 (error (message "Error running timer%s: %S"
322 (if (symbolp (timer--function timer))
323 (format " `%s'" (timer--function timer)) "")
324 err)))
325 (when (and retrigger
326 ;; If the timer's been canceled, don't "retrigger" it
327 ;; since it might still be in the copy of timer-list kept
328 ;; by keyboard.c:timer_check (bug#14156).
329 (memq timer timer-list))
330 (setf (timer--triggered timer) nil)))))
331
332 ;; This function is incompatible with the one in levents.el.
333 (defun timeout-event-p (event)
334 "Non-nil if EVENT is a timeout event."
335 (and (listp event) (eq (car event) 'timer-event)))
336 \f
337
338 (declare-function diary-entry-time "diary-lib" (s))
339
340 (defun run-at-time (time repeat function &rest args)
341 "Perform an action at time TIME.
342 Repeat the action every REPEAT seconds, if REPEAT is non-nil.
343 TIME should be one of: a string giving an absolute time like
344 \"11:23pm\" (the acceptable formats are those recognized by
345 `diary-entry-time'; note that such times are interpreted as times
346 today, even if in the past); a string giving a relative time like
347 \"2 hours 35 minutes\" (the acceptable formats are those
348 recognized by `timer-duration'); nil meaning now; a number of
349 seconds from now; a value from `encode-time'; or t (with non-nil
350 REPEAT) meaning the next integral multiple of REPEAT. REPEAT may
351 be an integer or floating point number. The action is to call
352 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 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 (defun run-with-timer (secs repeat function &rest args)
402 "Perform an action after a delay of SECS seconds.
403 Repeat the action every REPEAT seconds, if REPEAT is non-nil.
404 SECS and REPEAT may be integers or floating point numbers.
405 The action is to call FUNCTION with arguments ARGS.
406
407 This function returns a timer object which you can use in `cancel-timer'."
408 (interactive "sRun after delay (seconds): \nNRepeat interval: \naFunction: ")
409 (apply 'run-at-time secs repeat function args))
410
411 (defun add-timeout (secs function object &optional repeat)
412 "Add a timer to run SECS seconds from now, to call FUNCTION on OBJECT.
413 If REPEAT is non-nil, repeat the timer every REPEAT seconds.
414 This function is for compatibility; see also `run-with-timer'."
415 (run-with-timer secs repeat function object))
416
417 (defun run-with-idle-timer (secs repeat function &rest args)
418 "Perform an action the next time Emacs is idle for SECS seconds.
419 The action is to call FUNCTION with arguments ARGS.
420 SECS may be an integer, a floating point number, or the internal
421 time format returned by, e.g., `current-idle-time'.
422 If Emacs is currently idle, and has been idle for N seconds (N < SECS),
423 then it will call FUNCTION in SECS - N seconds from now. Using
424 SECS <= N is not recommended if this function is invoked from an idle
425 timer, because FUNCTION will then be called immediately.
426
427 If REPEAT is non-nil, do the action each time Emacs has been idle for
428 exactly SECS seconds (that is, only once for each time Emacs becomes idle).
429
430 This function returns a timer object which you can use in `cancel-timer'."
431 (interactive
432 (list (read-from-minibuffer "Run after idle (seconds): " nil nil t)
433 (y-or-n-p "Repeat each time Emacs is idle? ")
434 (intern (completing-read "Function: " obarray 'fboundp t))))
435 (let ((timer (timer-create)))
436 (timer-set-function timer function args)
437 (timer-set-idle-time timer secs repeat)
438 (timer-activate-when-idle timer t)
439 timer))
440 \f
441 (defvar with-timeout-timers nil
442 "List of all timers used by currently pending `with-timeout' calls.")
443
444 (defmacro with-timeout (list &rest body)
445 "Run BODY, but if it doesn't finish in SECONDS seconds, give up.
446 If we give up, we run the TIMEOUT-FORMS and return the value of the last one.
447 The timeout is checked whenever Emacs waits for some kind of external
448 event (such as keyboard input, input from subprocesses, or a certain time);
449 if the program loops without waiting in any way, the timeout will not
450 be detected.
451 \n(fn (SECONDS TIMEOUT-FORMS...) BODY)"
452 (declare (indent 1) (debug ((form body) body)))
453 (let ((seconds (car list))
454 (timeout-forms (cdr list))
455 (timeout (make-symbol "timeout")))
456 `(let ((-with-timeout-value-
457 (catch ',timeout
458 (let* ((-with-timeout-timer-
459 (run-with-timer ,seconds nil
460 (lambda () (throw ',timeout ',timeout))))
461 (with-timeout-timers
462 (cons -with-timeout-timer- with-timeout-timers)))
463 (unwind-protect
464 (progn ,@body)
465 (cancel-timer -with-timeout-timer-))))))
466 ;; It is tempting to avoid the `if' altogether and instead run
467 ;; timeout-forms in the timer, just before throwing `timeout'.
468 ;; But that would mean that timeout-forms are run in the deeper
469 ;; dynamic context of the timer, with inhibit-quit set etc...
470 (if (eq -with-timeout-value- ',timeout)
471 (progn ,@timeout-forms)
472 -with-timeout-value-))))
473
474 (defun with-timeout-suspend ()
475 "Stop the clock for `with-timeout'. Used by debuggers.
476 The idea is that the time you spend in the debugger should not
477 count against these timeouts.
478
479 The value is a list that the debugger can pass to `with-timeout-unsuspend'
480 when it exits, to make these timers start counting again."
481 (mapcar (lambda (timer)
482 (cancel-timer timer)
483 (list timer (time-subtract (timer--time timer) (current-time))))
484 with-timeout-timers))
485
486 (defun with-timeout-unsuspend (timer-spec-list)
487 "Restart the clock for `with-timeout'.
488 The argument should be a value previously returned by `with-timeout-suspend'."
489 (dolist (elt timer-spec-list)
490 (let ((timer (car elt))
491 (delay (cadr elt)))
492 (timer-set-time timer (time-add (current-time) delay))
493 (timer-activate timer))))
494
495 (defun y-or-n-p-with-timeout (prompt seconds default-value)
496 "Like (y-or-n-p PROMPT), with a timeout.
497 If the user does not answer after SECONDS seconds, return DEFAULT-VALUE."
498 (with-timeout (seconds default-value)
499 (y-or-n-p prompt)))
500 \f
501 (defconst timer-duration-words
502 (list (cons "microsec" 0.000001)
503 (cons "microsecond" 0.000001)
504 (cons "millisec" 0.001)
505 (cons "millisecond" 0.001)
506 (cons "sec" 1)
507 (cons "second" 1)
508 (cons "min" 60)
509 (cons "minute" 60)
510 (cons "hour" (* 60 60))
511 (cons "day" (* 24 60 60))
512 (cons "week" (* 7 24 60 60))
513 (cons "fortnight" (* 14 24 60 60))
514 (cons "month" (* 30 24 60 60)) ; Approximation
515 (cons "year" (* 365.25 24 60 60)) ; Approximation
516 )
517 "Alist mapping temporal words to durations in seconds.")
518
519 (defun timer-duration (string)
520 "Return number of seconds specified by STRING, or nil if parsing fails."
521 (let ((secs 0)
522 (start 0)
523 (case-fold-search t))
524 (while (string-match
525 "[ \t]*\\([0-9.]+\\)?[ \t]*\\([a-z]+[a-rt-z]\\)s?[ \t]*"
526 string start)
527 (let ((count (if (match-beginning 1)
528 (string-to-number (match-string 1 string))
529 1))
530 (itemsize (cdr (assoc (match-string 2 string)
531 timer-duration-words))))
532 (if itemsize
533 (setq start (match-end 0)
534 secs (+ secs (* count itemsize)))
535 (setq secs nil
536 start (length string)))))
537 (if (= start (length string))
538 secs
539 (if (string-match-p "\\`[0-9.]+\\'" string)
540 (string-to-number string)))))
541
542 (defun internal-timer-start-idle ()
543 "Mark all idle-time timers as once again candidates for running."
544 (dolist (timer timer-idle-list)
545 (if (timerp timer) ;; FIXME: Why test?
546 (setf (timer--triggered timer) nil))))
547 \f
548 (provide 'timer)
549
550 ;;; timer.el ends here