Previous: , Up: Time   [Index]


I.2.5 Timers

You can set up a timer to call a function at a specified future time or after a certain length of idleness. A timer is a special object that stores the information about the next invocation times and the function to invoke.

When Timers Can Run

Emacs cannot run timers at any arbitrary point in a Lisp program; it can run them only when Emacs could accept output from a subprocess: namely, while waiting or inside certain primitive functions such as sit-for or read-event which can wait. Therefore, a timer’s execution may be delayed if Emacs is busy. However, the time of execution is very precise if Emacs is idle.

Timers Inhibit Quitting

Emacs binds inhibit-quit to ‘t’ before calling the timer function, because quitting out of many timer functions can leave things in an inconsistent state. This is normally unproblematical because most timer functions don’t do a lot of work. If a timer function needs to allow quitting, it should use with-local-quit.

Timers Should Not Alter Buffer Contents

It is usually a bad idea for timer functions to alter buffer contents. When they do, they usually should call undo-boundary both before and after changing the buffer, to separate the timer’s changes from user commands’ changes and prevent a single undo entry from growing to be quite large.

Timers Should Not Call Functions that Wait

Timer functions should also avoid calling functions that cause Emacs to wait, such as sit-for (see Waiting). This can lead to unpredictable effects, since other timers (or even the same timer) can run while waiting. If a timer function needs to perform an action after a certain time has elapsed, it can do this by scheduling a new timer.

Timers Should Avoid Changing Match Data

If a timer function calls functions that can change the match data, it should save and restore the match data.


Previous: Time Calculations, Up: Time   [Index]