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è)派生類(lèi)
python中的線程提供了java線程功能的子集。
#!/usr/bin/env python from threading import Timer import time timer_interval=1 def 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ù)是用來(lái)讓主線程暫停一點(diǎn)時(shí)間再繼續(xù)執(zhí)行。
實(shí)例擴(kuò)展:
Python3定時(shí)器任務(wù)代碼
import time import sys import signal import datetime import 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_time def quit_sys(signum, frame): sys.exit() #接收C if __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中的簡(jiǎn)單定時(shí)器實(shí)例內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python的ORM框架中SQLAlchemy庫(kù)的查詢操作的教程
這篇文章主要介紹了Python的ORM框架中SQLAlchemy庫(kù)的查詢操作的教程,SQLAlchemy用來(lái)操作數(shù)據(jù)庫(kù)十分方便,需要的朋友可以參考下2015-04-04PyTorch?使用torchvision進(jìn)行圖片數(shù)據(jù)增廣
本文主要介紹了PyTorch?使用torchvision進(jìn)行圖片數(shù)據(jù)增廣,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-05-05深入掌握Python模塊創(chuàng)建導(dǎo)入和使用
這篇文章主要為大家介紹了深入掌握Python模塊創(chuàng)建導(dǎo)入和使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10python實(shí)現(xiàn)使用遺傳算法進(jìn)行圖片擬合
最近做項(xiàng)目需要圖像擬合,本文主要介紹了python實(shí)現(xiàn)使用遺傳算法進(jìn)行圖片擬合,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03python計(jì)算機(jī)視覺(jué)opencv矩形輪廓頂點(diǎn)位置確定
這篇文章主要為大家介紹了python計(jì)算機(jī)視覺(jué)opencv矩形輪廓頂點(diǎn)位置確定,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05