3

When running a function inside a timer, there are some constraints on whats possible.


Is it possible to detect if a function is running from a timer so an alternate code-path can be used?

The only solution I've found is to add advice on the caller to define a variable which the function being called can check, however this isn't such a nice solution as it may mean adding advice to many functions.

ideasman42
  • 8,375
  • 1
  • 28
  • 105

1 Answers1

2

All timers get processed in timer-event-handler, so you can add advice to that instead:

(defvar called-by-timer nil
  "Bound to t when a function is called by a timer.")

(advice-add 'timer-event-handler :around
            (lambda (oldfun &rest args)
              (let ((called-by-timer t))
                (apply oldfun args))))

(defun hello ()
  (message "%s %s" "Hello" (if called-by-timer "from timer" "from elsewhere")))

(hello)
(run-with-timer 1 nil #'hello)
d125q
  • 1,418
  • 5
  • 9