python——多線程thread

來源:互聯網
上載者:User

python通過thread模組支援多線程,文法也很簡潔,現在通過一個執行個體來看一下python中的多線程:

import threadimport time#保證只額外啟動一個線程isRunning=False#啟動的時間控制,測試時間是23點44分,所以定的是這個時間,可以用於指定定時任務的執行時間timer_hour=23timer_min=44#額外其他一個線程處理任務def another_thread():    print '[another_thread] is start...'    #聲明使用全域變數isRunning    global isRunning    #for迴圈類比任務執行    for i in range(3):        time.sleep(1)        print '[another_thread] time: %s ' % time.strftime('%Y-%m-%d %X',time.localtime())        print '[another_thread] Is Running: %s' % isRunning    #此處只是為了保證該任務一天只啟動一次,一分不會超過60秒    time.sleep(60)    print '[another_thread] is end...'    #該狀態只是為了保證該任務不會重複啟動,當然對於任務可以設定一個逾時時間,到時不結束自動終結    isRunning = Falseif __name__ == '__main__':    while True:        now = time.localtime()        print '[main_thread] time: %s' % time.strftime('%Y-%m-%d %X',now)        print '[main_thread] Is Running: %s' % isRunning        if now.tm_hour==timer_hour and now.tm_min==timer_min and not isRunning:            #進入任務前即置為True狀態,防止重複啟動            isRunning = True            #python開啟一個新的線程,從後面列印日誌的情況可以知道,並不會影響主線程的運行            thread.start_new_thread(another_thread,())                 time.sleep(1)

代碼執行後如下:

C:\Users\Captain\Desktop>python task.py[main_thread] time: 2013-07-31 23:44:56[main_thread] Is Running: False[another_thread] is start...[main_thread] time: 2013-07-31 23:44:57[another_thread] time: 2013-07-31 23:44:57[main_thread] Is Running: True[another_thread] Is Running: True[main_thread] time: 2013-07-31 23:44:58[another_thread] time: 2013-07-31 23:44:58[main_thread] Is Running: True[another_thread] Is Running: True[main_thread] time: 2013-07-31 23:44:59[another_thread] time: 2013-07-31 23:44:59[another_thread] Is Running: True[main_thread] Is Running: True[main_thread] time: 2013-07-31 23:45:00[main_thread] Is Running: True[main_thread] time: 2013-07-31 23:45:01[main_thread] Is Running: True[main_thread] time: 2013-07-31 23:45:02

該執行個體很簡單,可按照這個思路,應用於定時任務,心跳檢測,守護進程等實際情境中

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.