timer.el 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. ;;; timer.el --- run a function with args at some time in future
  2. ;; Copyright (C) 1996, 2001-2012 Free Software Foundation, Inc.
  3. ;; Maintainer: FSF
  4. ;; Package: emacs
  5. ;; This file is part of GNU Emacs.
  6. ;; GNU Emacs is free software: you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; GNU Emacs is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;; This package gives you the capability to run Emacs Lisp commands at
  18. ;; specified times in the future, either as one-shots or periodically.
  19. ;;; Code:
  20. ;; Layout of a timer vector:
  21. ;; [triggered-p high-seconds low-seconds usecs repeat-delay
  22. ;; function args idle-delay]
  23. ;; triggered-p is nil if the timer is active (waiting to be triggered),
  24. ;; t if it is inactive ("already triggered", in theory)
  25. (eval-when-compile (require 'cl))
  26. (defstruct (timer
  27. (:constructor nil)
  28. (:copier nil)
  29. (:constructor timer-create ())
  30. (:type vector)
  31. (:conc-name timer--))
  32. (triggered t)
  33. high-seconds low-seconds usecs repeat-delay function args idle-delay)
  34. (defun timerp (object)
  35. "Return t if OBJECT is a timer."
  36. (and (vectorp object) (= (length object) 8)))
  37. ;; Pseudo field `time'.
  38. (defun timer--time (timer)
  39. (list (timer--high-seconds timer)
  40. (timer--low-seconds timer)
  41. (timer--usecs timer)))
  42. (defsetf timer--time
  43. (lambda (timer time)
  44. (or (timerp timer) (error "Invalid timer"))
  45. (setf (timer--high-seconds timer) (pop time))
  46. (setf (timer--low-seconds timer)
  47. (if (consp time) (car time) time))
  48. (setf (timer--usecs timer) (or (and (consp time) (consp (cdr time))
  49. (cadr time))
  50. 0))))
  51. (defun timer-set-time (timer time &optional delta)
  52. "Set the trigger time of TIMER to TIME.
  53. TIME must be in the internal format returned by, e.g., `current-time'.
  54. If optional third argument DELTA is a positive number, make the timer
  55. fire repeatedly that many seconds apart."
  56. (setf (timer--time timer) time)
  57. (setf (timer--repeat-delay timer) (and (numberp delta) (> delta 0) delta))
  58. timer)
  59. (defun timer-set-idle-time (timer secs &optional repeat)
  60. "Set the trigger idle time of TIMER to SECS.
  61. SECS may be an integer, floating point number, or the internal
  62. time format (HIGH LOW USECS) returned by, e.g., `current-idle-time'.
  63. If optional third argument REPEAT is non-nil, make the timer
  64. fire each time Emacs is idle for that many seconds."
  65. (if (consp secs)
  66. (setf (timer--time timer) secs)
  67. (setf (timer--time timer) '(0 0 0))
  68. (timer-inc-time timer secs))
  69. (setf (timer--repeat-delay timer) repeat)
  70. timer)
  71. (defun timer-next-integral-multiple-of-time (time secs)
  72. "Yield the next value after TIME that is an integral multiple of SECS.
  73. More precisely, the next value, after TIME, that is an integral multiple
  74. of SECS seconds since the epoch. SECS may be a fraction."
  75. (let ((time-base (ash 1 16)))
  76. ;; Use floating point, taking care to not lose precision.
  77. (let* ((float-time-base (float time-base))
  78. (million 1000000.0)
  79. (time-usec (+ (* million
  80. (+ (* float-time-base (nth 0 time))
  81. (nth 1 time)))
  82. (nth 2 time)))
  83. (secs-usec (* million secs))
  84. (mod-usec (mod time-usec secs-usec))
  85. (next-usec (+ (- time-usec mod-usec) secs-usec))
  86. (time-base-million (* float-time-base million)))
  87. (list (floor next-usec time-base-million)
  88. (floor (mod next-usec time-base-million) million)
  89. (floor (mod next-usec million))))))
  90. (defun timer-relative-time (time secs &optional usecs)
  91. "Advance TIME by SECS seconds and optionally USECS microseconds.
  92. SECS may be either an integer or a floating point number."
  93. (let ((delta (if (floatp secs)
  94. (seconds-to-time secs)
  95. (list (floor secs 65536) (mod secs 65536)))))
  96. (if usecs
  97. (setq delta (time-add delta (list 0 0 usecs))))
  98. (time-add time delta)))
  99. (defun timer--time-less-p (t1 t2)
  100. "Say whether time value T1 is less than time value T2."
  101. (time-less-p (timer--time t1) (timer--time t2)))
  102. (defun timer-inc-time (timer secs &optional usecs)
  103. "Increment the time set in TIMER by SECS seconds and USECS microseconds.
  104. SECS may be a fraction. If USECS is omitted, that means it is zero."
  105. (setf (timer--time timer)
  106. (timer-relative-time (timer--time timer) secs usecs)))
  107. (defun timer-set-time-with-usecs (timer time usecs &optional delta)
  108. "Set the trigger time of TIMER to TIME plus USECS.
  109. TIME must be in the internal format returned by, e.g., `current-time'.
  110. The microsecond count from TIME is ignored, and USECS is used instead.
  111. If optional fourth argument DELTA is a positive number, make the timer
  112. fire repeatedly that many seconds apart."
  113. (setf (timer--time timer) time)
  114. (setf (timer--usecs timer) usecs)
  115. (setf (timer--repeat-delay timer) (and (numberp delta) (> delta 0) delta))
  116. timer)
  117. (make-obsolete 'timer-set-time-with-usecs
  118. "use `timer-set-time' and `timer-inc-time' instead."
  119. "22.1")
  120. (defun timer-set-function (timer function &optional args)
  121. "Make TIMER call FUNCTION with optional ARGS when triggering."
  122. (or (timerp timer)
  123. (error "Invalid timer"))
  124. (setf (timer--function timer) function)
  125. (setf (timer--args timer) args)
  126. timer)
  127. (defun timer--activate (timer &optional triggered-p reuse-cell idle)
  128. (if (and (timerp timer)
  129. (integerp (timer--high-seconds timer))
  130. (integerp (timer--low-seconds timer))
  131. (integerp (timer--usecs timer))
  132. (timer--function timer))
  133. (let ((timers (if idle timer-idle-list timer-list))
  134. last)
  135. ;; Skip all timers to trigger before the new one.
  136. (while (and timers (timer--time-less-p (car timers) timer))
  137. (setq last timers
  138. timers (cdr timers)))
  139. (if reuse-cell
  140. (progn
  141. (setcar reuse-cell timer)
  142. (setcdr reuse-cell timers))
  143. (setq reuse-cell (cons timer timers)))
  144. ;; Insert new timer after last which possibly means in front of queue.
  145. (cond (last (setcdr last reuse-cell))
  146. (idle (setq timer-idle-list reuse-cell))
  147. (t (setq timer-list reuse-cell)))
  148. (setf (timer--triggered timer) triggered-p)
  149. (setf (timer--idle-delay timer) idle)
  150. nil)
  151. (error "Invalid or uninitialized timer")))
  152. (defun timer-activate (timer &optional triggered-p reuse-cell)
  153. "Insert TIMER into `timer-list'.
  154. If TRIGGERED-P is t, make TIMER inactive (put it on the list, but
  155. mark it as already triggered). To remove it, use `cancel-timer'.
  156. REUSE-CELL, if non-nil, is a cons cell to reuse when inserting
  157. TIMER into `timer-list' (usually a cell removed from that list by
  158. `cancel-timer-internal'; using this reduces consing for repeat
  159. timers). If nil, allocate a new cell."
  160. (timer--activate timer triggered-p reuse-cell nil))
  161. (defun timer-activate-when-idle (timer &optional dont-wait reuse-cell)
  162. "Insert TIMER into `timer-idle-list'.
  163. This arranges to activate TIMER whenever Emacs is next idle.
  164. If optional argument DONT-WAIT is non-nil, set TIMER to activate
  165. immediately, or at the right time, if Emacs is already idle.
  166. REUSE-CELL, if non-nil, is a cons cell to reuse when inserting
  167. TIMER into `timer-idle-list' (usually a cell removed from that
  168. list by `cancel-timer-internal'; using this reduces consing for
  169. repeat timers). If nil, allocate a new cell."
  170. (timer--activate timer (not dont-wait) reuse-cell 'idle))
  171. (defalias 'disable-timeout 'cancel-timer)
  172. (defun cancel-timer (timer)
  173. "Remove TIMER from the list of active timers."
  174. (or (timerp timer)
  175. (error "Invalid timer"))
  176. (setq timer-list (delq timer timer-list))
  177. (setq timer-idle-list (delq timer timer-idle-list))
  178. nil)
  179. (defun cancel-timer-internal (timer)
  180. "Remove TIMER from the list of active timers or idle timers.
  181. Only to be used in this file. It returns the cons cell
  182. that was removed from the timer list."
  183. (let ((cell1 (memq timer timer-list))
  184. (cell2 (memq timer timer-idle-list)))
  185. (if cell1
  186. (setq timer-list (delq timer timer-list)))
  187. (if cell2
  188. (setq timer-idle-list (delq timer timer-idle-list)))
  189. (or cell1 cell2)))
  190. (defun cancel-function-timers (function)
  191. "Cancel all timers which would run FUNCTION.
  192. This affects ordinary timers such as are scheduled by `run-at-time',
  193. and idle timers such as are scheduled by `run-with-idle-timer'."
  194. (interactive "aCancel timers of function: ")
  195. (dolist (timer timer-list)
  196. (if (eq (timer--function timer) function)
  197. (setq timer-list (delq timer timer-list))))
  198. (dolist (timer timer-idle-list)
  199. (if (eq (timer--function timer) function)
  200. (setq timer-idle-list (delq timer timer-idle-list)))))
  201. ;; Record the last few events, for debugging.
  202. (defvar timer-event-last nil
  203. "Last timer that was run.")
  204. (defvar timer-event-last-1 nil
  205. "Next-to-last timer that was run.")
  206. (defvar timer-event-last-2 nil
  207. "Third-to-last timer that was run.")
  208. (defvar timer-max-repeats 10
  209. "*Maximum number of times to repeat a timer, if many repeats are delayed.
  210. Timer invocations can be delayed because Emacs is suspended or busy,
  211. or because the system's time changes. If such an occurrence makes it
  212. appear that many invocations are overdue, this variable controls
  213. how many will really happen.")
  214. (defun timer-until (timer time)
  215. "Calculate number of seconds from when TIMER will run, until TIME.
  216. TIMER is a timer, and stands for the time when its next repeat is scheduled.
  217. TIME is a time-list."
  218. (float-time (time-subtract time (timer--time timer))))
  219. (defun timer-event-handler (timer)
  220. "Call the handler for the timer TIMER.
  221. This function is called, by name, directly by the C code."
  222. (setq timer-event-last-2 timer-event-last-1)
  223. (setq timer-event-last-1 timer-event-last)
  224. (setq timer-event-last timer)
  225. (let ((inhibit-quit t))
  226. (if (timerp timer)
  227. (let (retrigger cell)
  228. ;; Delete from queue. Record the cons cell that was used.
  229. (setq cell (cancel-timer-internal timer))
  230. ;; Re-schedule if requested.
  231. (if (timer--repeat-delay timer)
  232. (if (timer--idle-delay timer)
  233. (timer-activate-when-idle timer nil cell)
  234. (timer-inc-time timer (timer--repeat-delay timer) 0)
  235. ;; If real time has jumped forward,
  236. ;; perhaps because Emacs was suspended for a long time,
  237. ;; limit how many times things get repeated.
  238. (if (and (numberp timer-max-repeats)
  239. (< 0 (timer-until timer (current-time))))
  240. (let ((repeats (/ (timer-until timer (current-time))
  241. (timer--repeat-delay timer))))
  242. (if (> repeats timer-max-repeats)
  243. (timer-inc-time timer (* (timer--repeat-delay timer)
  244. repeats)))))
  245. (timer-activate timer t cell)
  246. (setq retrigger t)))
  247. ;; Run handler.
  248. ;; We do this after rescheduling so that the handler function
  249. ;; can cancel its own timer successfully with cancel-timer.
  250. (condition-case nil
  251. ;; Timer functions should not change the current buffer.
  252. ;; If they do, all kinds of nasty surprises can happen,
  253. ;; and it can be hellish to track down their source.
  254. (save-current-buffer
  255. (apply (timer--function timer) (timer--args timer)))
  256. (error nil))
  257. (if retrigger
  258. (setf (timer--triggered timer) nil)))
  259. (error "Bogus timer event"))))
  260. ;; This function is incompatible with the one in levents.el.
  261. (defun timeout-event-p (event)
  262. "Non-nil if EVENT is a timeout event."
  263. (and (listp event) (eq (car event) 'timer-event)))
  264. (declare-function diary-entry-time "diary-lib" (s))
  265. (defun run-at-time (time repeat function &rest args)
  266. "Perform an action at time TIME.
  267. Repeat the action every REPEAT seconds, if REPEAT is non-nil.
  268. TIME should be one of: a string giving an absolute time like
  269. \"11:23pm\" (the acceptable formats are those recognized by
  270. `diary-entry-time'; note that such times are interpreted as times
  271. today, even if in the past); a string giving a relative time like
  272. \"2 hours 35 minutes\" (the acceptable formats are those
  273. recognized by `timer-duration'); nil meaning now; a number of
  274. seconds from now; a value from `encode-time'; or t (with non-nil
  275. REPEAT) meaning the next integral multiple of REPEAT. REPEAT may
  276. be an integer or floating point number. The action is to call
  277. FUNCTION with arguments ARGS.
  278. This function returns a timer object which you can use in `cancel-timer'."
  279. (interactive "sRun at time: \nNRepeat interval: \naFunction: ")
  280. (or (null repeat)
  281. (and (numberp repeat) (< 0 repeat))
  282. (error "Invalid repetition interval"))
  283. ;; Special case: nil means "now" and is useful when repeating.
  284. (if (null time)
  285. (setq time (current-time)))
  286. ;; Special case: t means the next integral multiple of REPEAT.
  287. (if (and (eq time t) repeat)
  288. (setq time (timer-next-integral-multiple-of-time (current-time) repeat)))
  289. ;; Handle numbers as relative times in seconds.
  290. (if (numberp time)
  291. (setq time (timer-relative-time (current-time) time)))
  292. ;; Handle relative times like "2 hours 35 minutes"
  293. (if (stringp time)
  294. (let ((secs (timer-duration time)))
  295. (if secs
  296. (setq time (timer-relative-time (current-time) secs)))))
  297. ;; Handle "11:23pm" and the like. Interpret it as meaning today
  298. ;; which admittedly is rather stupid if we have passed that time
  299. ;; already. (Though only Emacs hackers hack Emacs at that time.)
  300. (if (stringp time)
  301. (progn
  302. (require 'diary-lib)
  303. (let ((hhmm (diary-entry-time time))
  304. (now (decode-time)))
  305. (if (>= hhmm 0)
  306. (setq time
  307. (encode-time 0 (% hhmm 100) (/ hhmm 100) (nth 3 now)
  308. (nth 4 now) (nth 5 now) (nth 8 now)))))))
  309. (or (consp time)
  310. (error "Invalid time format"))
  311. (let ((timer (timer-create)))
  312. (timer-set-time timer time repeat)
  313. (timer-set-function timer function args)
  314. (timer-activate timer)
  315. timer))
  316. (defun run-with-timer (secs repeat function &rest args)
  317. "Perform an action after a delay of SECS seconds.
  318. Repeat the action every REPEAT seconds, if REPEAT is non-nil.
  319. SECS and REPEAT may be integers or floating point numbers.
  320. The action is to call FUNCTION with arguments ARGS.
  321. This function returns a timer object which you can use in `cancel-timer'."
  322. (interactive "sRun after delay (seconds): \nNRepeat interval: \naFunction: ")
  323. (apply 'run-at-time secs repeat function args))
  324. (defun add-timeout (secs function object &optional repeat)
  325. "Add a timer to run SECS seconds from now, to call FUNCTION on OBJECT.
  326. If REPEAT is non-nil, repeat the timer every REPEAT seconds.
  327. This function is for compatibility; see also `run-with-timer'."
  328. (run-with-timer secs repeat function object))
  329. (defun run-with-idle-timer (secs repeat function &rest args)
  330. "Perform an action the next time Emacs is idle for SECS seconds.
  331. The action is to call FUNCTION with arguments ARGS.
  332. SECS may be an integer, a floating point number, or the internal
  333. time format (HIGH LOW USECS) returned by, e.g., `current-idle-time'.
  334. If Emacs is currently idle, and has been idle for N seconds (N < SECS),
  335. then it will call FUNCTION in SECS - N seconds from now.
  336. If REPEAT is non-nil, do the action each time Emacs has been idle for
  337. exactly SECS seconds (that is, only once for each time Emacs becomes idle).
  338. This function returns a timer object which you can use in `cancel-timer'."
  339. (interactive
  340. (list (read-from-minibuffer "Run after idle (seconds): " nil nil t)
  341. (y-or-n-p "Repeat each time Emacs is idle? ")
  342. (intern (completing-read "Function: " obarray 'fboundp t))))
  343. (let ((timer (timer-create)))
  344. (timer-set-function timer function args)
  345. (timer-set-idle-time timer secs repeat)
  346. (timer-activate-when-idle timer t)
  347. timer))
  348. (defvar with-timeout-timers nil
  349. "List of all timers used by currently pending `with-timeout' calls.")
  350. (defmacro with-timeout (list &rest body)
  351. "Run BODY, but if it doesn't finish in SECONDS seconds, give up.
  352. If we give up, we run the TIMEOUT-FORMS and return the value of the last one.
  353. The timeout is checked whenever Emacs waits for some kind of external
  354. event (such as keyboard input, input from subprocesses, or a certain time);
  355. if the program loops without waiting in any way, the timeout will not
  356. be detected.
  357. \n(fn (SECONDS TIMEOUT-FORMS...) BODY)"
  358. (declare (indent 1) (debug ((form body) body)))
  359. (let ((seconds (car list))
  360. (timeout-forms (cdr list))
  361. (timeout (make-symbol "timeout")))
  362. `(let ((-with-timeout-value-
  363. (catch ',timeout
  364. (let* ((-with-timeout-timer-
  365. (run-with-timer ,seconds nil
  366. (lambda () (throw ',timeout ',timeout))))
  367. (with-timeout-timers
  368. (cons -with-timeout-timer- with-timeout-timers)))
  369. (unwind-protect
  370. ,@body
  371. (cancel-timer -with-timeout-timer-))))))
  372. ;; It is tempting to avoid the `if' altogether and instead run
  373. ;; timeout-forms in the timer, just before throwing `timeout'.
  374. ;; But that would mean that timeout-forms are run in the deeper
  375. ;; dynamic context of the timer, with inhibit-quit set etc...
  376. (if (eq -with-timeout-value- ',timeout)
  377. (progn ,@timeout-forms)
  378. -with-timeout-value-))))
  379. (defun with-timeout-suspend ()
  380. "Stop the clock for `with-timeout'. Used by debuggers.
  381. The idea is that the time you spend in the debugger should not
  382. count against these timeouts.
  383. The value is a list that the debugger can pass to `with-timeout-unsuspend'
  384. when it exits, to make these timers start counting again."
  385. (mapcar (lambda (timer)
  386. (cancel-timer timer)
  387. (list timer (time-subtract (timer--time timer) (current-time))))
  388. with-timeout-timers))
  389. (defun with-timeout-unsuspend (timer-spec-list)
  390. "Restart the clock for `with-timeout'.
  391. The argument should be a value previously returned by `with-timeout-suspend'."
  392. (dolist (elt timer-spec-list)
  393. (let ((timer (car elt))
  394. (delay (cadr elt)))
  395. (timer-set-time timer (time-add (current-time) delay))
  396. (timer-activate timer))))
  397. (defun y-or-n-p-with-timeout (prompt seconds default-value)
  398. "Like (y-or-n-p PROMPT), with a timeout.
  399. If the user does not answer after SECONDS seconds, return DEFAULT-VALUE."
  400. (with-timeout (seconds default-value)
  401. (y-or-n-p prompt)))
  402. (defconst timer-duration-words
  403. (list (cons "microsec" 0.000001)
  404. (cons "microsecond" 0.000001)
  405. (cons "millisec" 0.001)
  406. (cons "millisecond" 0.001)
  407. (cons "sec" 1)
  408. (cons "second" 1)
  409. (cons "min" 60)
  410. (cons "minute" 60)
  411. (cons "hour" (* 60 60))
  412. (cons "day" (* 24 60 60))
  413. (cons "week" (* 7 24 60 60))
  414. (cons "fortnight" (* 14 24 60 60))
  415. (cons "month" (* 30 24 60 60)) ; Approximation
  416. (cons "year" (* 365.25 24 60 60)) ; Approximation
  417. )
  418. "Alist mapping temporal words to durations in seconds.")
  419. (defun timer-duration (string)
  420. "Return number of seconds specified by STRING, or nil if parsing fails."
  421. (let ((secs 0)
  422. (start 0)
  423. (case-fold-search t))
  424. (while (string-match
  425. "[ \t]*\\([0-9.]+\\)?[ \t]*\\([a-z]+[a-rt-z]\\)s?[ \t]*"
  426. string start)
  427. (let ((count (if (match-beginning 1)
  428. (string-to-number (match-string 1 string))
  429. 1))
  430. (itemsize (cdr (assoc (match-string 2 string)
  431. timer-duration-words))))
  432. (if itemsize
  433. (setq start (match-end 0)
  434. secs (+ secs (* count itemsize)))
  435. (setq secs nil
  436. start (length string)))))
  437. (if (= start (length string))
  438. secs
  439. (if (string-match-p "\\`[0-9.]+\\'" string)
  440. (string-to-number string)))))
  441. (provide 'timer)
  442. ;;; timer.el ends here