Python多線程和定時器
多線程
在Python中任務由上到下順序執行,若需要將多個任務同時執行需要引入多線程。
多線程示例代碼如下:
import threading
runWebVedio(i):
...
fun_timer(x):
...
th1 = threading.Thread(target= runWebVedio, args=(1,), name="thread1")
th2 = threading.Thread(target= fun_timer, args=(x,), name="thread2")
th1.start()
th2.start()
上述代碼創建了兩個線程,分別調用了已經定義的兩個函數,args屬性中傳入函數所需要的參數,使用start()函數開始線程的運行。
定時器
有時會遇到每隔一定時間重複執行某個操作的需求,這個時候定時器是很好的選擇。
定時器的示例代碼如下:
import threading
def fun_timer():
print('Hello Timer!')
global timer
timer = threading.Timer(5, fun_timer)
timer.start()
timer = threading.Timer(1, fun_timer)
timer.start()
上述程序運行一秒後執行fun_timer()函數,此後每隔五秒執行一次。