溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么在Python中實現一個守護進程

發布時間:2021-04-16 17:54:24 來源:億速云 閱讀:161 作者:Leah 欄目:開發技術

本篇文章為大家展示了怎么在Python中實現一個守護進程,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。

import time
import threading


def fun():
  print "start fun"
  time.sleep(2)
  print "end fun"
print "main thread"
t1 = threading.Thread(target=fun,args=())
#t1.setDaemon(True)
t1.start()
time.sleep(1)
print "main thread end"

結果:

main thread
start fun
main thread end
end fun

結論:程序在等待子線程結束,才退出了。

設置:setDaemon 為True

import time
import threading
def fun():
  print "start fun"
  time.sleep(2)
  print "end fun"

print "main thread"
t1 = threading.Thread(target=fun,args=())

t1.setDaemon(True)

t1.start()
time.sleep(1)
print "main thread end"

結果:

main thread
start fun
main thread end

結論:程序在主線程結束后,直接退出了。 導致子線程沒有運行完。

守護進程可以通過調用isAlive(), 來監視其他線程是否是存活的。

如果死掉的話就重新建立一個工作線程,啟動起來(這里要注意不能使用原來的線程讓它start(),因為這個線程已經結束了,內存中的實例已經釋放掉了,所以使用這個方法會報錯)。

#coding=utf-8
import time
from threading import Thread
 
 
class ticker(Thread):
  def run(self):
    while True:
      print time.time()
      if (time.time() > 1470883000):
        break
        pass
      time.sleep(3)     
      pass
    pass
 
class moniter(Thread):
  def run(self):
    while True:
      global T
      if (T.isAlive()):
        print 't is alive'
      else :
        print 't is dead'
        T = ticker()
        T.start()
      print 'checking '
      time.sleep(5)
      pass
    pass
T = ticker()
T.start()
 
mo = moniter()
mo.start()

上述內容就是怎么在Python中實現一個守護進程,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女