python 定時器,每天凌晨3點執行方法


'''
Created on 2018-4-20

例子:每天凌晨3點執行func方法
'''
import datetime
import threading

def func():
print("haha")
#如果需要循環調用,就要添加以下方法
timer = threading.Timer(86400, func)
timer.start()

# 獲取現在時間
now_time = datetime.datetime.now()
# 獲取明天時間
next_time = now_time + datetime.timedelta(days=+1)
next_year = next_time.date().year
next_month = next_time.date().month
next_day = next_time.date().day
# 獲取明天3點時間
next_time = datetime.datetime.strptime(str(next_year)+"-"+str(next_month)+"-"+str(next_day)+" 03:00:00", "%Y-%m-%d %H:%M:%S")
# # 獲取昨天時間
# last_time = now_time + datetime.timedelta(days=-1)

# 獲取距離明天3點時間,單位為秒
timer_start_time = (next_time - now_time).total_seconds()
print(timer_start_time)
# 54186.75975


#定時器,參數為(多少時間后執行,單位為秒,執行的方法)
timer = threading.Timer(timer_start_time, func)
timer.start()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM