Python中实现时间延迟的方法

Python中实现时间延迟的方法

技术背景

在Python编程中,有时需要在程序执行过程中引入时间延迟,例如控制任务执行的时间间隔、模拟现实世界中的延迟等。Python提供了多种方法来实现时间延迟,每种方法适用于不同的场景。

实现步骤

使用time.sleep()方法

time.sleep()是Python中最常用的实现时间延迟的方法,它可以暂停当前线程的执行指定的秒数。以下是简单的示例:

1
2
3
4
import time
print('Hello')
time.sleep(5) # 延迟5秒
print('Bye')

使用threading.Timer

threading.Timer类可以在指定的时间后执行一个函数,并且不会阻塞主线程的执行。示例如下:

1
2
3
4
5
6
7
8
9
10
from threading import Timer

delay_in_sec = 2

def hello(delay_in_sec):
print(f'function called after {delay_in_sec} seconds')

t = Timer(delay_in_sec, hello, [delay_in_sec])
t.start()
print("Started")

使用asyncio.sleep()方法(Python 3.4及以上版本)

asyncio.sleep()用于异步编程中的时间延迟。示例代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import asyncio
from datetime import datetime

@asyncio.coroutine
def countdown(iteration_name, countdown_sec):
while countdown_sec > 0:
print(f'{iteration_name} iterates: {countdown_sec} seconds')
yield from asyncio.sleep(1)
countdown_sec -= 1

loop = asyncio.get_event_loop()
tasks = [asyncio.ensure_future(countdown('First Count', 2)),
asyncio.ensure_future(countdown('Second Count', 3))]

start_time = datetime.utcnow()
loop.run_until_complete(asyncio.wait(tasks))
loop.close()

print(f'total running time: {datetime.utcnow() - start_time}')

使用matplotlib.pyplot.pause()方法

如果你已经导入了matplotlib库,可以使用pyplot.pause()方法来实现时间延迟。示例如下:

1
2
from matplotlib import pyplot as plt
plt.pause(5) # 暂停程序5秒

使用Tkinterafter()方法

在使用Tkinter进行图形界面编程时,应使用after()方法来实现时间延迟,而不是time.sleep(),因为time.sleep()会阻塞界面的更新。示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
import tkinter as tk

root = tk.Tk()
print('Hello')

def ohhi():
print('Oh, hi!')

root.after(5000, ohhi) # 5000毫秒(即5秒)后调用ohhi函数
print('Bye')

root.mainloop()

使用while循环实现延迟

可以通过while循环结合time.time()来实现简单的时间延迟:

1
2
3
4
5
import time
start = time.time()
while time.time() - start < 10: # 运行10秒
pass
# 执行后续任务

核心代码

time.sleep()核心代码

1
2
import time
time.sleep(2.5)

threading.Timer核心代码

1
2
3
4
5
6
7
from threading import Timer

def party_time():
print('hooray!')

t = Timer(3, party_time)
t.start()

asyncio.sleep()核心代码

1
2
3
4
5
6
7
8
import asyncio

async def main():
print("Start")
await asyncio.sleep(2)
print("End")

asyncio.run(main())

最佳实践

  • 单线程场景:如果只是简单的延迟任务,使用time.sleep()是最方便的选择。
  • 多线程场景:如果需要在不阻塞主线程的情况下延迟执行某个函数,可以使用threading.Timer
  • 异步编程场景:在异步编程中,使用asyncio.sleep()可以充分利用异步特性,提高程序的性能。
  • 图形界面编程:在使用Tkinter等图形界面库时,使用after()方法来避免界面冻结。

常见问题

使用time.sleep()导致Tkinter界面冻结

如果在Tkinter程序中使用time.sleep(),会导致界面冻结,无法响应用户操作。解决方法是使用after()方法。

异步编程中不使用asyncio.sleep()

在异步编程中,如果使用time.sleep(),会阻塞整个事件循环,影响程序的异步性能。应使用asyncio.sleep()

threading.Timer的取消问题

如果需要取消已经启动的threading.Timer,可以调用cancel()方法。示例如下:

1
2
3
4
5
6
7
8
from threading import Timer

def hello():
print('Hello')

t = Timer(5, hello)
t.start()
t.cancel() # 取消定时器

Python中实现时间延迟的方法
https://119291.xyz/posts/2025-05-09.python-time-delay-implementation/
作者
ww
发布于
2025年5月9日
许可协议