Emacs定时任务
Emacs提供实现定时任务的方式有两种:MidnightMode和run-with-timer函数
run-with-timer
这个函数的调用语法如下:
(run-with-timer SECS REPEAT FUNCTION &rest ARGS)
意思是延迟SECS秒后执行FUNCTION函数对应的行为。如果REPEAT参数非空(non-nil),之后则每REPEAT秒重复执行一遍FUNCTION函数。这个函数调用参数ARGS。有意思的是,SECS和REPEAT可为整数和浮点数。
这个函数返回一个timer对象,该对象可以在cancel-timer函数中调用。其中cancel-timer函数调用语法如下:
(cancel-timer TIMER)
它的意思是将TIMER从运行的timers中移除。
Midnight Mode
Midnight mode使用如下:
- 引入Midnight包
(require 'midnight)
- 定义midnight(就是一个午夜时间点)。如定义上午4:30为午夜时间,有下面两种定义方式:
(midnight-delay-set 'midnight-delay "4:30am")
(midnight-delay-set 'midnight-delay 16200) ;; (eq (* 4.5 60 60) "4:30am")
- 将要在午夜时间点开始执行的函数添加到midnight-hook
(add-hook 'midnight-hook (lambda
(with-current-buffer "*cvs*"
(call-interactively 'cvs-update))))
(add-hook 'midnight-hook 'calendar)
- 取消执行
(cancel-timer midnight-timer)
- 如果想在一天当中执行多次midnight的行为,修改midnight-period变量值,如下每两个小时执行一次
(setq midnight-period 7200) ;; (eq (* 2 60 60) "2 hours")
其他定时任务函数
run-with-idle-timer
(run-with-idle-timer SECS REPEAT FUNCTION &rest args)
意思是当下次emacs空闲SECS秒时执行函数FUNCTION行为。如果REPEAT为nil,只执行一次。否则,每次空闲重复执行。这个函数也返回一个timer对象。