View on GitHub

Ment.Niu

To eke out a living Live is better than burning

Python 中使用 sched 严格控制程序运行时间间隔

由于我们在监控的过程中需要采集样本点,故我们设定的两次采样点的时间间隔是需要严格控制的,不能因为机器上的其他任务调度原因延迟我们的采样时间准确性。

原有的运行一次程序之后sleep一段时间再运行一次的方式不够准确,本文介绍使用python中的sched严格控制执行时间 定时执行程序

我们所介绍的方式是在特定的时间执行程序,下面以程序加注释的方式说明


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sched
import sys,time

# 每次调用的函数,打印round和执行的时间
def event(round):
    print "Round %s,time:%s" %(round,time.time())

# 初始化scheduler
scheduler = sched.scheduler(time.time, time.sleep)
# 获得执行调度的初始时间
inittime = time.time()

# 总运行次数
total_round = 10
# 运行间隔
interval = 1
# 计数
update = 0

while update <= interval * total_round:

    # 设定调度 使用enterabs设定真实执行时间
    # 参数:1 执行时间(time.time格式)2 优先级 3 执行的函数 4 函数参数
    scheduler.enterabs(inittime + update, 1, event, (update,))

    # 执行调度,会一直阻塞在这里,直到函数执行结束
    scheduler.run()

    # 输出屏幕
    sys.stdout.flush()

    # 增加计数值
    update = update + interval

通过这种方式,我们可以准确的获得两次采样的数据值和间隔时间,通过种种方式计算的使用率是相对比较准确的