定时运行
在每天指定时间完成某项任务
import time
while True:
time_now = time.strftime("%H:%M:%S", time.localtime()) # 刷新
if time_now == "15:30:10": #此处设置每天定时的时间
# 此处3行替换为需要执行的动作
print("hello")
subject = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + " 定时发送测试"
print(subject)
time.sleep(2) # 因为以秒定时,所以暂停2秒,使之不会在1秒内执行多次
每分钟指定‘秒数’运行一次
import time
while True:
time_now = time.strftime("%S", time.localtime()) # 刷新
if time_now == "10": #此处设置每天定时的时间
# 此处3行替换为需要执行的动作
print("hello")
subject = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + " 定时发送测试"
print(subject)
time.sleep(2) # 因为以秒定时,所以暂停2秒,使之不会在1秒内执行多次
利用目标时间与当前时间的差来触发
import time
def doFirst():
from datetime import datetime #, timedelta
#读取当时的系统时间
curTime = datetime.now()
#设置想要触发的目标时间,此处设置为17:48:30
desTime = curTime.replace(hour=14, minute=45, second=10, microsecond=0)
delta = desTime-curTime
#把时间差转换成以秒为单位的时间
skipSeconds = int(delta.total_seconds())
if skipSeconds == 0:
return True
else:
if skipSeconds < 0:
skipSeconds += 24*60*60 #设置触发周期,此处设置为1天
print("还有 %d 秒触发" % skipSeconds)
return False
while True:
if doFirst():
#插入数据
print('成功啦!')
time.sleep(24*60*60-60) #触发周期为1天,当还剩1分钟时,开始倒计时
time.sleep(1)
总结