python3.x - python每隔10秒運(yùn)行一個(gè)指定函數(shù)怎么實(shí)現(xiàn)呢?等待過程不能中斷主線程!
問題描述
如題,求教!
問題解答
回答1:可以通過另開一條線程, 去專門做這件事情, py2代碼如下, 如果是py3請(qǐng)自行調(diào)整下語法
# coding: utf8import threadingimport time# 真正要執(zhí)行的函數(shù)def t1(): print (’ok’)# 每隔10秒鐘執(zhí)行def t2(): while 1:t1()time.sleep(10)if __name__ == ’__main__’: t = threading.Thread(target=t2) t.start() # 此處寫你主線程要處理的事情..... t.join()回答2:
threading.Timer
import threading as thdimport timedef fn(): print(time.time()) thd.Timer(10,fn).start() fn()回答3:
如果直接開子進(jìn)程的話,退出主進(jìn)程時(shí)子進(jìn)程會(huì)一直存在, 建議設(shè)置成守護(hù)進(jìn)程
import sysimport signalimport threadingimport timefrom datetime import datetimedef quit(signum, frame): sys.exit()def process_fun(): while True:print datetime.now()time.sleep(1)if __name__ == ’__main__’: try:signal.signal(signal.SIGINT, quit)signal.signal(signal.SIGTERM, quit)p = threading.Thread(target=process_fun)#注冊(cè)成為主進(jìn)程p.setDaemon(True)p.start()#如果沒有主進(jìn)程, 就用循環(huán)代理while True: pass except Exception as e:pass回答4:
可以考慮Advanced Python Scheduler(http://apscheduler.readthedoc...能夠進(jìn)行極其復(fù)雜的定時(shí)設(shè)計(jì),每個(gè)幾秒幾分鐘,或者是某天的具體一刻等等,可以阻塞進(jìn)程,可以在后臺(tái),全部按照你的要求。
回答5:# -*- coding: utf-8 -*-import geventimport timeclass Timer(object): '''定時(shí)器,定時(shí)執(zhí)行指定的函數(shù) ''' def __init__(self, start, interval):'''@start, int, 延遲執(zhí)行的秒數(shù)@interval, int, 每次執(zhí)行的間隔秒數(shù)'''self.start = startself.interval = interval def run(self, func, *args, **kwargs):'''運(yùn)行定時(shí)器:param func: callable, 要執(zhí)行的函數(shù)'''time.sleep(self.start)while True: func(*args, **kwargs) time.sleep(self.interval)def send_message(): passif __name__ == '__main__': scheduler = Timer(5, 10 * 60) gevent.spawn(scheduler.run(send_message))回答6:Python任務(wù)調(diào)度模塊 – APScheduler(點(diǎn)擊查看)
APScheduler是一個(gè)Python定時(shí)任務(wù)框架,使用起來十分方便。提供了基于日期、固定時(shí)間間隔以及crontab類型的任務(wù),并且可以持久化任務(wù)、并以daemon方式運(yùn)行應(yīng)用。
下面是一個(gè)簡單的例子,每隔10秒打印一次hello world
from apscheduler.schedulers.blocking import BlockingSchedulerdef my_job(): print ’hello world’ sched = BlockingScheduler()sched.add_job(my_job, ’interval’, seconds=10)sched.start()回答7:
#-*- coding:utf8 -*- import multiprocessingimport timedef f(): print time.ctime(),’這是子進(jìn)程,每10S執(zhí)行一次’def work(): while 1: f() time.sleep(10)if __name__ == ’__main__’: p = multiprocessing.Process(target=work,) p.start() p.deamon = True while 1:print ’這是主進(jìn)程,每1秒執(zhí)行一次’time.sleep(1)
執(zhí)行結(jié)果:
相關(guān)文章:
1. mysql日期類型默認(rèn)值’0000-00-00’ 報(bào)錯(cuò)2. 求救一下,用新版的phpstudy,數(shù)據(jù)庫過段時(shí)間會(huì)消失是什么情況?3. mysql replace 死鎖4. mysql - C#連接數(shù)據(jù)庫時(shí)一直這一句出問題int i = cmd.ExecuteNonQuery();5. MYSQL 根據(jù)兩個(gè)字段值查詢 但兩個(gè)值的位置可能是互換的,這個(gè)怎么查?6. extra沒有加載出來7. android - 安卓做前端,PHP做后臺(tái)服務(wù)器 有什么需要注意的?8. javascript - 微信網(wǎng)頁開發(fā)從菜單進(jìn)入頁面后,按返回鍵沒有關(guān)閉瀏覽器而是刷新當(dāng)前頁面,求解決?9. php傳對(duì)應(yīng)的id值為什么傳不了啊有木有大神會(huì)的看我下方截圖10. mysql - ubuntu開啟3306端口失敗,有什么辦法可以解決?
