python每隔一段时间做一个事情

时间:2023-03-10 03:05:06
python每隔一段时间做一个事情
 #!/usr/bin/env python
#coding:utf8
#Author:lsp
#Date:下午2:17:54
#Version:0.1
#Function: 每隔一段时间做一个事情
from datetime import date, time, datetime, timedelta #要做的事情
def work():
print "hello world." def runTask(func, day=0, hour=0, min=0, second=0):
# Init time
now = datetime.now()
strnow = now.strftime('%Y-%m-%d %H:%M:%S')
print "now:",strnow
# First next run time
period = timedelta(days=day, hours=hour, minutes=min, seconds=second)
next_time = now + period
strnext_time = next_time.strftime('%Y-%m-%d %H:%M:%S')
print "next run:",strnext_time
while True:
# Get system current time
iter_now = datetime.now()
iter_now_time = iter_now.strftime('%Y-%m-%d %H:%M:%S')
if str(iter_now_time) == str(strnext_time):
# Get every start work time
print "start work: %s" % iter_now_time
# Call task func
work()
print "task done."
# Get next iteration time
iter_time = iter_now + period
strnext_time = iter_time.strftime('%Y-%m-%d %H:%M:%S')
print "next_iter: %s" % strnext_time
# Continue next iteration
continue # runTask(work, min=0.5)
runTask(work(), day=0, hour=0, min=0,second=10)