python3.x - python每隔10秒運行一個指定函數怎么實現呢?等待過程不能中斷主線程!
問題描述
如題,求教!
問題解答
回答1:可以通過另開一條線程, 去專門做這件事情, py2代碼如下, 如果是py3請自行調整下語法
# coding: utf8import threadingimport time# 真正要執行的函數def t1(): print (’ok’)# 每隔10秒鐘執行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:
如果直接開子進程的話,退出主進程時子進程會一直存在, 建議設置成守護進程
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)#注冊成為主進程p.setDaemon(True)p.start()#如果沒有主進程, 就用循環代理while True: pass except Exception as e:pass回答4:
可以考慮Advanced Python Scheduler(http://apscheduler.readthedoc...能夠進行極其復雜的定時設計,每個幾秒幾分鐘,或者是某天的具體一刻等等,可以阻塞進程,可以在后臺,全部按照你的要求。
回答5:# -*- coding: utf-8 -*-import geventimport timeclass Timer(object): '''定時器,定時執行指定的函數 ''' def __init__(self, start, interval):'''@start, int, 延遲執行的秒數@interval, int, 每次執行的間隔秒數'''self.start = startself.interval = interval def run(self, func, *args, **kwargs):'''運行定時器:param func: callable, 要執行的函數'''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任務調度模塊 – APScheduler(點擊查看)
APScheduler是一個Python定時任務框架,使用起來十分方便。提供了基于日期、固定時間間隔以及crontab類型的任務,并且可以持久化任務、并以daemon方式運行應用。
下面是一個簡單的例子,每隔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(),’這是子進程,每10S執行一次’def work(): while 1: f() time.sleep(10)if __name__ == ’__main__’: p = multiprocessing.Process(target=work,) p.start() p.deamon = True while 1:print ’這是主進程,每1秒執行一次’time.sleep(1)
執行結果:
相關文章:
