python定时执行某程序脚本(每隔一段时间执行指定函数)

import os
import time
def print_ts(message):
    print "[%s] %s"%(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), message)
def run(interval, command):
    print_ts("-"*100)
    print_ts("Command %s"%command)
    print_ts("Starting every %s seconds."%interval)
    print_ts("-"*100)
    while True:
        try:
            # sleep for the remaining seconds of interval
            time_remaining = interval-time.time()%interval
            print_ts("Sleeping until %s (%s seconds)..."%((time.ctime(time.time()+time_remaining)), time_remaining))
            time.sleep(time_remaining)
            print_ts("Starting command.")
            # execute the command
            status = os.system(command)
            print_ts("-"*100)
            print_ts("Command status = %s."%status)
        except Exception, e:
            print e
if __name__=="__main__":
    interval = 5
    command = r"ls"
    run(interval, command)

原创文章,作者:江海志,如若转载,请注明出处:https://jianghaizhi.com/bckf/1307.html

Like (0)
Previous 2017-09-24 07:37
Next 2017-10-15

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注