python定时任务
2016-06-22 00:00
387 查看
摘要: 可自行根据需求扩充,可调整精度
# -*- coding:utf-8 -*- ''' Created on 2016年5月20日 @author: chenyangbo ''' import time import heapq from threading import Timer TIME_ACCURACY = 1 # 时间精度,时间精度不是越小越好!你的Task每次循环超过了这个值,将影响准确度 class Scheduler(object): tasks = [] @staticmethod def add(task): heapq.heappush(Scheduler.tasks, (task.get_runtime(), task)) @staticmethod def run(): now = time.time() while Scheduler.tasks and now >= Scheduler.tasks[0][0]: _,task = heapq.heappop(Scheduler.tasks) task.call() if task.is_cycle(): task.up_runtime() Scheduler.add(task) t = Timer(TIME_ACCURACY,Scheduler.run) t.start() ''' 定时任务 func:要定时执行的方法 args:函数的参数(tuple) 执行start()此定时器生效 ''' class Task(object): def __init__(self, func, args = ()): self._func = func self._args = args self._runtime = time.time() self._interval = 0 self._cycle = False def call(self): self._func(*self._args) def up_runtime(self): self._runtime += self._interval def is_cycle(self): return self._cycle def get_runtime(self): return self._runtime def start(self): Scheduler.add(self) ''' 作用:简单定时任务 runtime:开始时间(时间戳) ''' class NormalTask(Task): def __init__(self, runtime, func, args = ()): Task.__init__(self, func, args) self._runtime = runtime ''' 作用:倒计时定时任务 countdown:倒计时,这个时间后开始执行(单位:秒) ''' class CountdownTask(Task): def __init__(self, countdown, func, args = ()): Task.__init__(self, func, args) self._runtime += countdown ''' 作用:循环定时任务 interval:循环周期(单位:秒) ''' class IntervalTask(Task): def __init__(self, interval, func, args = ()): Task.__init__(self, func, args) self._interval = interval self._cycle = True def test(x, y): print time.time() print x + y if "__main__" == __name__: Scheduler.run() now = time.time() t = IntervalTask(2, test, (1,2)) t.start()
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法