您的位置:首頁技術文章
文章詳情頁

Python如何實現定時器功能

瀏覽:7日期:2022-07-24 09:21:02

Timer: 隔一定時間調用一個函數,如果想實現每隔一段時間就調用一個函數的話,就要在Timer調用的函數中,再次設置Timer。Timer是Thread的一個派生類

python中的線程提供了java線程功能的子集。

#!/usr/bin/env pythonfrom threading import Timerimport timetimer_interval=1def delayrun(): print ’running’t=Timer(timer_interval,delayrun)t.start()while True: time.sleep(0.1) print ’main running’

t是一個Timer對象。delay一秒鐘之后執行delayrun函數。

其中time.sleep函數是用來讓主線程暫停一點時間再繼續執行。

實例擴展:

Python3定時器任務代碼

import timeimport sysimport signalimport datetimeimport threading#定時器def schedule_update(): t = threading.Timer(0, event_func) t.setDaemon(True) t.start()#執行函數def event_func(): now_time = datetime.datetime.now().strftime(’%Y-%m-%d %H:%M:%S’) print(now_time) exec_update() #update_openvas_dbs_from_cache() interval_time = delay_time() t = threading.Timer(interval_time, event_func) t.setDaemon(True) t.start()#取時間點def delay_time(): # now time now_time = datetime.datetime.now() # tomorrow time 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 # get tomorrow 00:00 next_time = datetime.datetime.strptime(str(next_year)+'-'+str(next_month)+'-'+str(next_day)+' 00:00:00', '%Y-%m-%d %H:%M:%S') # get secondes delay_time = (next_time - now_time).total_seconds() return delay_timedef quit_sys(signum, frame): sys.exit()#接收Cif __name__ == '__main__': try: signal.signal(signal.SIGINT, quit_sys) signal.signal(signal.SIGTERM, quit_sys) schedule_update() print('schedule_update server starting up...nHit Ctrl-C to quit.n') while 1: time.sleep(1) except Exception as e: print(e)

到此這篇關于Python如何實現定時器功能的文章就介紹到這了,更多相關Python中的簡單定時器實例內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Python 編程
相關文章:
国产综合久久一区二区三区