python每隔N秒运行指定函数的方法

Python019

python每隔N秒运行指定函数的方法,第1张

python每隔N秒运行指定函数方法

这篇文章主要介绍了python每隔N秒运行指定函数的方法,涉及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"ipconfig"

run(interval, command)

希望本文所述对大家的Python程序设计有所帮助。

可以使用apscheduler模块

Python code?

123456789101112131415161718

from apscheduler.schedulers.blocking import BlockingSchedulerfrom datetime import datetimeimport timeimport os def tick():print 'Tick! The time is: %s' % datetime.now() #每隔三秒执行一次if __name__ == '__main__':scheduler = BlockingScheduler()scheduler.add_job(tick,'cron',second='*/3',hour='*')print 'Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C')try:scheduler.start()except KeyboardInterrupt,SystemExit:scheduler.shutdown()

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

[python] view plain copy

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)