Python如何實(shí)現(xiàn)定時(shí)器功能
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對象。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)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. idea配置jdk的操作方法2. idea導(dǎo)入maven項(xiàng)目的方法3. 在Python中使用K-Means聚類和PCA主成分分析進(jìn)行圖像壓縮4. ThinkPHP6使用最新版本Endroid/QrCode生成二維碼的方法實(shí)例5. XMLHTTP資料6. python csv一些基本操作總結(jié)7. Python源碼解析之List8. asp知識(shí)整理筆記4(問答模式)9. HTML DOM setInterval和clearInterval方法案例詳解10. Spring如何基于xml實(shí)現(xiàn)聲明式事務(wù)控制
