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