成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁技術(shù)文章
文章詳情頁

Python如何實(shí)現(xiàn)定時(shí)器功能

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

Timer: 隔一定時(shí)間調(diào)用一個(gè)函數(shù),如果想實(shí)現(xiàn)每隔一段時(shí)間就調(diào)用一個(gè)函數(shù)的話,就要在Timer調(diào)用的函數(shù)中,再次設(shè)置Timer。Timer是Thread的一個(gè)派生類

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是一個(gè)Timer對(duì)象。delay一秒鐘之后執(zhí)行delayrun函數(shù)。

其中time.sleep函數(shù)是用來讓主線程暫停一點(diǎn)時(shí)間再繼續(xù)執(zhí)行。

實(shí)例擴(kuò)展:

Python3定時(shí)器任務(wù)代碼

import timeimport sysimport signalimport datetimeimport threading#定時(shí)器def schedule_update(): t = threading.Timer(0, event_func) t.setDaemon(True) t.start()#執(zhí)行函數(shù)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()#取時(shí)間點(diǎn)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)

到此這篇關(guān)于Python如何實(shí)現(xiàn)定時(shí)器功能的文章就介紹到這了,更多相關(guān)Python中的簡單定時(shí)器實(shí)例內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Python 編程
相關(guān)文章: