Skip to content

Instantly share code, notes, and snippets.

@hackerain
Last active December 28, 2015 18:39
Show Gist options
  • Save hackerain/7544209 to your computer and use it in GitHub Desktop.
Save hackerain/7544209 to your computer and use it in GitHub Desktop.
python sched 定时循环任务
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sched
import sys,time
# action function, and add another event to queue.
def event(action_time):
print "action_time:%s" % (action_time)
scheduler.enterabs(action_time + 5, 1, event, (action_time + 5,))
# 初始化scheduler
scheduler = sched.scheduler(time.time, time.sleep)
# 获得执行调度的初始时间
inittime = time.time()
# 设定调度 使用enterabs设定真实执行时间
# 参数:1 执行时间(time.time格式)2 优先级 3 执行的函数 4 函数参数
scheduler.enterabs(inittime, 1, event, (inittime,))
# 执行调度,会一直阻塞在这里,直到函数执行结束
scheduler.run()
@hackerain
Copy link
Author

sched内部是使用堆排序做的一个优先级队列,以time排序,所以在action function中可以通过enter*()向队列中再添加event,达到让它一直执行任务的目的

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment