您的位置:首页 > 编程语言 > Python开发

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 定时任务