好记性不如铅笔头

python && jython, 编程

【转】Python3 – 时间处理与定时任务

本文转自【 http://www.pythontab.com/html/2013/pythonjichu_0119/146.html 】,有删改。

CONTENTS

Python3 – 时间处理与定时任务

无论哪种编程语言,时间肯定都是非常重要的部分,今天来看一下python如何来处理时间和python定时任务,注意咯:本篇所讲是python3版本的实现,在python2版本中的实现略有不同,有时间会再写一篇以便大家区分。

。。。。。。。

。。。。。。。

4.反复执行某个命令

#! /usr/bin/env python
#coding=utf-8
# 以需要的时间间隔执行某个命令 
    
import time, os 
    
def re_exe(cmd, inc = 60): 
    while True: 
        os.system(cmd); 
        time.sleep(inc) 
    
re_exe("echo %time%", 5)

5.定时任务

#! /usr/bin/env python
#coding=utf-8
#这里需要引入三个模块
import time, os, sched 
    
# 第一个参数确定任务的时间,返回从某个特定的时间到现在经历的秒数 
# 第二个参数以某种人为的方式衡量时间 
schedule = sched.scheduler(time.time, time.sleep) 
    
def perform_command(cmd, inc): 
    os.system(cmd) 
        
def timming_exe(cmd, inc = 60): 
    # enter用来安排某事件的发生时间,从现在起第n秒开始启动 
    schedule.enter(inc, 0, perform_command, (cmd, inc)) 
    # 持续运行,直到计划时间队列变成空为止 
    schedule.run() 
        
    
print("show time after 10 seconds:") 
timming_exe("echo %time%", 10)

6.利用sched实现周期调用

#! /usr/bin/env python
#coding=utf-8
import time, os, sched 
    
# 第一个参数确定任务的时间,返回从某个特定的时间到现在经历的秒数 
# 第二个参数以某种人为的方式衡量时间 
schedule = sched.scheduler(time.time, time.sleep) 
    
def perform_command(cmd, inc): 
    # 安排inc秒后再次运行自己,即周期运行 
    schedule.enter(inc, 0, perform_command, (cmd, inc)) 
    os.system(cmd) 
        
def timming_exe(cmd, inc = 60): 
    # enter用来安排某事件的发生时间,从现在起第n秒开始启动 
    schedule.enter(inc, 0, perform_command, (cmd, inc)) 
    # 持续运行,直到计划时间队列变成空为止 
    schedule.run() 
        
print("show time after 10 seconds:") 
timming_exe("echo %time%", 10)

 

发表评论

15 − 9 =

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据