Synch with BBDB v2.34.
[elisp/gnus.git-] / contrib / timer.el
1 ;;; timer.el --- run a function with args at some time in future.
2
3 ;; Copyright (C) 1996 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., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, 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 (require 'itimer)
32
33 (fset 'timer-create 'make-itimer)
34
35 (fset 'timerp 'itimerp)
36
37 ;(defvar timer-idle-list nil
38 ;  "List of active idle-time timers in order of increasing time")
39 (defvaralias 'timer-idle-list 'itimer-list)
40 (defvaralias 'timer-list 'itimer-list)
41
42
43 (defun timer-set-time (timer time &optional delta)
44   "Set the trigger time of TIMER to TIME.
45 TIME must be in the internal format returned by, e.g., `current-time'.
46 If optional third argument DELTA is a non-zero integer, make the timer
47 fire repeatedly that many seconds apart."
48   (set-itimer-value timer (itimer-time-difference time (current-time)))
49   (and delta (check-nonnegative-number delta))
50   (and delta (set-itimer-restart timer delta))
51   timer)
52
53 (defun timer-set-idle-time (timer secs &optional repeat)
54   "Set the trigger idle time of TIMER to SECS.
55 If optional third argument REPEAT is non-nil, make the timer
56 fire each time Emacs is idle for that many seconds."
57   (set-itimer-is-idle timer t)
58   (set-itimer-value timer secs)
59   (when repeat
60     (set-itimer-restart timer secs))
61   timer)
62
63 (defun timer-relative-time (time secs &optional usecs)
64   "Advance TIME by SECS seconds and optionally USECS microseconds.
65 SECS may be a fraction."
66   (let ((high (car time))
67         (low (if (consp (cdr time)) (nth 1 time) (cdr time)))
68         (micro (if (numberp (car-safe (cdr-safe (cdr time))))
69                    (nth 2 time)
70                  0)))
71     ;; Add
72     (if usecs (setq micro (+ micro usecs)))
73     (if (floatp secs)
74         (setq micro (+ micro (floor (* 1000000 (- secs (floor secs)))))))
75     (setq low (+ low (floor secs)))
76
77     ;; Normalize
78     (setq low (+ low (/ micro 1000000)))
79     (setq micro (mod micro 1000000))
80     (setq high (+ high (/ low 65536)))
81     (setq low (logand low 65535))
82
83     (list high low (and (/= micro 0) micro))))
84
85 (defun timer-inc-time (timer secs &optional usecs)
86   "Increment the time set in TIMER by SECS seconds and USECS microseconds.
87 SECS may be a fraction."
88   (let ((time (itimer-value timer)))
89     (setq time (+ time secs (if (and usecs (fboundp 'lisp-float-type))
90                                 (/ usecs (float 1000000))
91                               0)))
92     (set-itimer-value timer time)))
93
94 (defun timer-set-time-with-usecs (timer time usecs &optional delta)
95   "Set the trigger time of TIMER to TIME.
96 TIME must be in the internal format returned by, e.g., `current-time'.
97 If optional third argument DELTA is a non-zero integer, make the timer
98 fire repeatedly that many seconds apart."
99   (let ((list (list nil nil nil)))
100     (setcar list (car time))
101     (setcar (nthcdr 1 list) (if (consp (cdr time))
102                                 (car (cdr time))
103                               (cdr time)))
104     (setcar (nthcdr 2 list) usecs)
105     (set-itimer-value timer (itimer-time-difference list (current-time)))
106     (set-itimer-restart timer delta)
107     timer))
108
109 (defun timer-set-function (timer function &optional args)
110   "Make TIMER call FUNCTION with optional ARGS when triggering."
111   (set-itimer-function timer function)
112   (set-itimer-function-arguments timer args)
113   (set-itimer-uses-arguments timer t)
114   timer)
115 \f
116 (defun timer-activate (timer)
117   "Put TIMER on the list of active timers."
118   (activate-itimer timer))
119
120 (defun timer-activate-when-idle (timer)
121   "Arrange to activate TIMER whenever Emacs is next idle."
122   (set-itimer-is-idle timer t)
123   ;(set-itimer-uses-arguments timer nil)
124   ;(unless (memq timer timer-idle-list)
125     ;(setq timer-idle-list (cons timer timer-idle-list)))
126   (activate-itimer timer))
127
128 ;; can't do this, different kind of timer
129 ;;(defalias 'disable-timeout 'cancel-timer)
130
131 (defun cancel-timer (timer)
132   "Remove TIMER from the list of active timers."
133   ;(setq timer-idle-list (delq timer timer-idle-list))
134   (delete-itimer timer))
135
136 (defun cancel-function-timers (function)
137   "Cancel all timers scheduled by `run-at-time' which would run FUNCTION."
138   (interactive "aCancel timers of function: ")
139   (let ((p itimer-list))
140     (while p
141       (if (eq function (itimer-function p))
142           (progn
143             (setq p (cdr p))
144             (delete-itimer (car p)))
145         (setq p (cdr p))))))
146 \f
147 ;;;###autoload
148 (defun run-at-time (time repeat function &rest args)
149   "Perform an action after a delay of SECS seconds.
150 Repeat the action every REPEAT seconds, if REPEAT is non-nil.
151 TIME should be a string like \"11:23pm\", nil meaning now, a number of seconds
152 from now, or a value from `encode-time'.
153 REPEAT may be an integer or floating point number.
154 The action is to call FUNCTION with arguments ARGS.
155
156 This function returns a timer object which you can use in `cancel-timer'."
157   (interactive "sRun at time: \nNRepeat interval: \naFunction: ")
158
159   ;; Special case: nil means "now" and is useful when repeating.
160   (if (null time)
161       (setq time (current-time)))
162
163   ;; Handle numbers as relative times in seconds.
164   (if (numberp time)
165       (setq time (timer-relative-time (current-time) time)))
166
167   ;; Handle relative times like "2 hours and 35 minutes"
168   (if (stringp time)
169       (let ((secs (timer-duration time)))
170         (if secs
171             (setq time (timer-relative-time (current-time) secs)))))
172
173   ;; Handle "11:23pm" and the like.  Interpret it as meaning today
174   ;; which admittedly is rather stupid if we have passed that time
175   ;; already.  (Though only Emacs hackers hack Emacs at that time.)
176   (if (stringp time)
177       (progn
178         (require 'diary-lib)
179         (let ((hhmm (diary-entry-time time))
180               (now (decode-time)))
181           (if (>= hhmm 0)
182               (setq time
183                     (encode-time 0 (% hhmm 100) (/ hhmm 100) (nth 3 now)
184                                  (nth 4 now) (nth 5 now) (nth 8 now)))))))
185
186   (or (consp time)
187       (error "Invalid time format"))
188
189   (or (null repeat)
190       (numberp repeat)
191       (error "Invalid repetition interval"))
192
193   (let ((timer (timer-create)))
194     (timer-set-time timer time repeat)
195     (timer-set-function timer function args)
196     (timer-activate timer)
197     timer))
198
199 ;;;###autoload
200 (defun run-with-timer (secs repeat function &rest args)
201   "Perform an action after a delay of SECS seconds.
202 Repeat the action every REPEAT seconds, if REPEAT is non-nil.
203 SECS and REPEAT may be integers or floating point numbers.
204 The action is to call FUNCTION with arguments ARGS.
205
206 This function returns a timer object which you can use in `cancel-timer'."
207   (interactive "sRun after delay (seconds): \nNRepeat interval: \naFunction: ")
208   (apply 'run-at-time secs repeat function args))
209
210 ;;;###autoload
211 (defun run-with-idle-timer (secs repeat function &rest args)
212   "Perform an action the next time Emacs is idle for SECS seconds.
213 If REPEAT is non-nil, do this each time Emacs is idle for SECS seconds.
214 SECS may be an integer or a floating point number.
215 The action is to call FUNCTION with arguments ARGS.
216
217 This function returns a timer object which you can use in `cancel-timer'."
218   (interactive
219    (list (read-from-minibuffer "Run after idle (seconds): " nil nil t)
220          (y-or-n-p "Repeat each time Emacs is idle? ")
221          (intern (completing-read "Function: " obarray 'fboundp t))))
222   (let ((timer (timer-create)))
223     (timer-set-function timer function args)
224     (timer-set-idle-time timer secs repeat)
225     (timer-activate-when-idle timer)
226     timer))
227 \f
228 (defun with-timeout-handler (tag)
229   (throw tag 'timeout))
230
231 ;;;###autoload (put 'with-timeout 'lisp-indent-function 1)
232
233 ;;;###autoload
234 (defmacro with-timeout (list &rest body)
235   "Run BODY, but if it doesn't finish in SECONDS seconds, give up.
236 If we give up, we run the TIMEOUT-FORMS and return the value of the last one.
237 The call should look like:
238  (with-timeout (SECONDS TIMEOUT-FORMS...) BODY...)
239 The timeout is checked whenever Emacs waits for some kind of external
240 event \(such as keyboard input, input from subprocesses, or a certain time);
241 if the program loops without waiting in any way, the timeout will not
242 be detected."
243   (let ((seconds (car list))
244         (timeout-forms (cdr list)))
245     `(let ((with-timeout-tag (cons nil nil))
246            with-timeout-value with-timeout-timer)
247        (if (catch with-timeout-tag
248              (progn
249                (setq with-timeout-timer
250                      (run-with-timer ,seconds nil
251                                       'with-timeout-handler
252                                       with-timeout-tag))
253                (setq with-timeout-value (progn . ,body))
254                nil))
255            (progn . ,timeout-forms)
256          (cancel-timer with-timeout-timer)
257          with-timeout-value))))
258
259 (defun y-or-n-p-with-timeout (prompt seconds default-value)
260   "Like (y-or-n-p PROMPT), with a timeout.
261 If the user does not answer after SECONDS seconds, return DEFAULT-VALUE."
262   (with-timeout (seconds default-value)
263     (y-or-n-p prompt)))
264 \f
265 (defvar timer-duration-words
266   (list (cons "microsec" 0.000001)
267         (cons "microsecond" 0.000001)
268         (cons "millisec" 0.001)
269         (cons "millisecond" 0.001)
270         (cons "sec" 1)
271         (cons "second" 1)
272         (cons "min" 60)
273         (cons "minute" 60)
274         (cons "hour" (* 60 60))
275         (cons "day" (* 24 60 60))
276         (cons "week" (* 7 24 60 60))
277         (cons "fortnight" (* 14 24 60 60))
278         (cons "month" (* 30 24 60 60))    ; Approximation
279         (cons "year" (* 365.25 24 60 60)) ; Approximation
280         )
281   "Alist mapping temporal words to durations in seconds")
282
283 (defun timer-duration (string)
284   "Return number of seconds specified by STRING, or nil if parsing fails."
285   (let ((secs 0)
286         (start 0)
287         (case-fold-search t))
288     (while (string-match
289             "[ \t]*\\([0-9.]+\\)?[ \t]*\\([a-z]+[a-rt-z]\\)s?[ \t]*"
290             string start)
291       (let ((count (if (match-beginning 1)
292                        (string-to-number (match-string 1 string))
293                      1))
294             (itemsize (cdr (assoc (match-string 2 string)
295                                   timer-duration-words))))
296         (if itemsize
297             (setq start (match-end 0)
298                   secs (+ secs (* count itemsize)))
299           (setq secs nil
300                 start (length string)))))
301     (if (= start (length string))
302         secs
303       (if (string-match "\\`[0-9.]+\\'" string)
304           (string-to-number string)))))
305 \f
306 (provide 'timer)
307
308 ;;; timer.el ends here