def work():
print "hello work"
def runTaskOnly(func, day=0, hour=0, min=0, second=0):
now = datetime.now()
strnow = now.strftime('%Y-%m-%d %H:%M:%S')
print "现在时间:",strnow
period = timedelta(days=day, hours=hour, minutes=min, seconds=second)
print "间隔时间:",period
next_time = now + period
strnext_time = next_time.strftime('%Y-%m-%d %H:%M:%S')
print "首次运行时间:",strnext_time
while True:
iter_now = datetime.now()
iter_now_time = iter_now.strftime('%Y-%m-%d %H:%M:%S')
if str(iter_now_time) == str(strnext_time):
print "任务开始: %s" % iter_now_time
func()
print "执行完成."
break
def runTaskMore(func, day=0, hour=0, min=0, second=0):
# Init time
now = datetime.now()
strnow = now.strftime('%Y-%m-%d %H:%M:%S')
print "现在时间:",strnow
# First next run time
period = timedelta(days=day, hours=hour, minutes=min, seconds=second)
print "间隔时间:",period
next_time = now + period
strnext_time = next_time.strftime('%Y-%m-%d %H:%M:%S')
print "首次运行时间:",strnext_time
while True:
iter_now = datetime.now()
iter_now_time = iter_now.strftime('%Y-%m-%d %H:%M:%S')
if str(iter_now_time) == str(strnext_time):
print "任务开始: %s" % iter_now_time
func()
print "执行完成"
iter_time = iter_now + period
strnext_time = iter_time.strftime('%Y-%m-%d %H:%M:%S')
print "再次运行时间: %s" % strnext_time
continue
runTaskOnly(work, day=1, hour=1, min=2)#间隔1天1小时2分钟后执行
runTaskMore(work, day=1, hour=1, min=2)#每隔1天1小时2分钟执行一次
Python定时任务
于 2022-02-23 16:35:34 首次发布