Python中的时间除了可以计算外,在延迟和暂停方面也有所涉及。之前学爬虫的时候用的是暂停功能,那么在多线程中为了使线程之间的有序运行,我们通常会使用time.sleep()对其中的一个线程进行阻拦挂起。下面我们就time.sleep()的概念、语法、参数、返回值、在线程中的实例带来介绍。
1.说明
sleep() 方法暂停给定秒数后执行程序。该参数可以是一个浮点数来表示一个更精确的睡眠时间。
实际中止时间可能不到所请求的,因为任何捕获信号将终止sleep()接下来执行该信号捕捉的程序。
2.语法
time.sleep(t)
3.参数
t – 推迟执行的秒数。
4.返回值
该函数没有返回值。
5.实例
import threading
import time
def thread1():
while True:
time.sleep(1)
print(time.strftime('%H:%M:%S'),'hahaha')
def thread2():
while True:
time.sleep(2)
print(time.strftime('%H:%M:%S'),'lalala')
thread_thred1 = threading.Thread(target=thread1)
thread_thred1.start()
thread_thread2 = threading.Thread(target=thread2)
thread_thread2.start()
以上就是time.sleep()在python线程中的使用,大家学会后,在线程中如果想要某个线程先执行,可以选择time.sleep()的方法先延迟其他线程的运行。
更多关于time.sleep()在python中使用相关推荐阅读:
PyThon中time strftime()函数用法
python中如何使用函数time.sleep()?