您可以考虑使用sched.scheduler
而不是threading.Timer
此处。有一些区别需要注意:
sched.scheduler
在主进程中运行所有内容,而不是在线程中。
- 如果当前进程花费的时间超过
delay
几秒,则计划的事件将在当前调用完成后interval
开始
。threading.Timer
工作方式不同——如果完成的工作
interval
超过一个小时,就会有多个线程
interval
同时运行。
我猜你真的不希望多个interval
同时运行,所以sched.scheduler
在这里可能比threading.Timer
.
import timeit
import sched
import time
import logging
import sys
logger = logging.getLogger(__name__)
logging.basicConfig(level = logging.DEBUG,
format = '%(threadName)s: %(asctime)s: %(message)s',
datefmt = '%H:%M:%S')
schedule = sched.scheduler(timeit.default_timer, time.sleep)
delay = 5 # change to 3600 to schedule event in 1 hour
def interval():
logger.info('All work and no play makes Jack a dull boy.')
schedule.enter(delay = delay, priority = 1, action = interval, argument = ())
# Uncomment this to see how scheduled events are delayed if interval takes a
# long time.
# time.sleep(10)
schedule.enter(delay = 0, priority = 1, action = interval, argument = ())
try:
schedule.run()
except (KeyboardInterrupt, SystemExit):
print('Exiting')
sys.exit()