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()
以上這篇python 定時器,實現每天凌晨3點執行的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持碼農之家。
Python定時器實例代碼
在實際應用中,我們經常需要使用定時器去觸發一些事件。Python中通過線程實現定時器timer,其使用非常簡單。看示例:
import threading
def fun_timer():
print('Hello Timer!')
timer = threading.Timer(1, fun_timer)
timer.start()
輸出結果:
Hello Timer!
Process finished with exit code 0
注意,只輸出了一次,程序就結束了,顯然不是我們想要的結果。看Timer類中的解釋性描述:
"""Call a function after a specified number of seconds"""
一段時間后調用一個函數,但并沒有說要循環調用該函數。因此,修改如下:
def fun_timer():
print('Hello Timer!')
global timer
timer = threading.Timer(5.5, fun_timer)
timer.start()
timer = threading.Timer(1, fun_timer)
timer.start()
輸出結果:
Hello Timer!
Hello Timer!
Hello Timer!
Hello Timer!
............
定時器工作正常。
在使用Python定時器時需要注意如下4個方面:
(1)定時器構造函數主要有2個參數,第一個參數為時間,第二個參數為函數名,第一個參數表示多長時間后調用后面第二個參數指明的函數。第二個參數注意是函數對象,進行參數傳遞,用函數名(如fun_timer)表示該對象,不能寫成函數執行語句fun_timer(),不然會報錯。用type查看下,可以看出兩者的區別。
print(type(fun_timer()))
print(type(fun_timer))
輸出:
Hello Timer!
(2)必須在定時器執行函數內部重復構造定時器,因為定時器構造后只執行1次,必須循環調用。
(3)定時器間隔單位是秒,可以是浮點數,如5.5,0.02等,在執行函數fun_timer內部和外部中給的值可以不同。如上例中第一次執行fun_timer是1秒后,后面的都是5.5秒后執行。
(4)可以使用cancel停止定時器的工作,如下例:
# -*- coding: utf-8 -*-
import threading
import time
def fun_timer():
print('Hello Timer!')
global timer
timer = threading.Timer(5.5, fun_timer)
timer.start()
timer = threading.Timer(1, fun_timer)
timer.start()
time.sleep(15) # 15秒后停止定時器
timer.cancel()
輸出:
Hello Timer!
Hello Timer!
Hello Timer!
Process finished with exit code 0
下面是一個Python寫的定時器,定時精度可調節,分享給大家。
# -* coding: utf-8 -*-
import sys
import os
import getopt
import threading
import time
def Usage():
usage_str = '''說明:
\t定時器
\timer.py -h 顯示本幫助信息,也可以使用--help選項
\timer.py -d num 指定一個延時時間(以毫秒為單位)
\t 也可以使用--duration=num選項
'''
print(usage_str)
def args_proc(argv):
'''處理命令行參數'''
try:
opts, args = getopt.getopt(sys.argv[1:], 'hd:', ['help', 'duration='])
except getopt.GetoptError as err:
print('錯誤!請為腳本指定正確的命令行參數。\n')
Usage()
sys.exit(255)
if len(opts) < 1:
print('使用提示:缺少必須的參數。')
Usage()
sys.exit(255)
usr_argvs = {}
for op, value in opts:
if op in ('-h', '--help'):
Usage()
sys.exit(1)
elif op in ('-d', '--duration'):
if int(value) <= 0:
print('錯誤!指定的參數值%s無效。\n' % (value))
Usage()
sys.exit(2)
else:
usr_argvs['-d'] = int(value)
else:
print('unhandled option')
sys.exit(3)
return usr_argvs
def timer_proc(interval_in_millisecond):
loop_interval = 10# 定時精度,也是循環間隔時間(毫秒),也是輸出信息刷新間隔時間,它不能大于指定的最大延時時間,否則可能導致無任何輸出
t = interval_in_millisecond / loop_interval
while t >= 0:
min = (t * loop_interval) / 1000 / 60
sec = (t * loop_interval) / 1000 % 60
millisecond = (t * loop_interval) % 1000
print('\rThe remaining time:%02d:%02d:%03d...' % ( min, sec, millisecond ), end = '\t\t')
time.sleep(loop_interval / 1000)
t -= 1
if millisecond != 0:
millisecond = 0
print('\rThe remaining time:%02d:%02d:%03d...' % ( min, sec, millisecond ), end = '\t\t')
print()
# 應用程序入口
if __name__ == '__main__':
usr_argvs = {}
usr_argvs = args_proc(sys.argv)
for argv in usr_argvs:
if argv in ( '-d', '--duration'):
timer_proc(usr_argvs[argv])
else:
continue
總結
以上就是本文關于Python定時器實例代碼的全部內容,希望對大家有所幫助。歡迎參閱:Python生成數字圖片代碼分享、Python列表刪除的三種方法代碼分享、13個最常用的Python深度學習庫介紹等,有什么問題可以隨時留言,歡迎大家交流參考。
以上就是本次給大家分享的關于java的全部知識點內容總結,大家還可以在下方相關文章里找到相關文章進一步學習,感謝大家的閱讀和支持。