我如何 运行 延迟在后台执行任务?
How do I run a task in the background with a delay?
我有以下代码:
import time
def wait10seconds():
for i in range(10):
time.sleep(1)
return 'Counted to 10!'
print(wait10seconds())
print('test')
现在我的问题是如何在不交换 2 行的情况下在执行函数 wait10seconds()
之前使 print('test')
运行。
我希望输出如下:
test
Counted to 10!
有人知道如何解决这个问题吗?
你可以用 Threads
来做这个
喜欢:
from threading import Thread
my_thread = Thread(target=wait10seconds) # Create a new thread that exec the function
my_thread.start() # start it
print('test') # print the test
my_thread.join() # wait for the function to end
如果您使用的是 python 3.5+,您可以使用 asyncio:
import asyncio
async def wait10seconds():
for i in range(10):
await asyncio.sleep(1)
return 'Counted to 10!'
print(asyncio.run(wait10seconds()))
asyncio.run
是 python 3.7 的新功能,对于 python 3.5 和 3.6,您将无法使用 asyncio.run
但您可以通过以下方式实现相同的目的直接与 event_loop 合作
您可以使用 Timer。摘自 Python 文档页面:
def hello():
print("hello, world")
t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed
我有以下代码:
import time
def wait10seconds():
for i in range(10):
time.sleep(1)
return 'Counted to 10!'
print(wait10seconds())
print('test')
现在我的问题是如何在不交换 2 行的情况下在执行函数 wait10seconds()
之前使 print('test')
运行。
我希望输出如下:
test
Counted to 10!
有人知道如何解决这个问题吗?
你可以用 Threads
来做这个
喜欢:
from threading import Thread
my_thread = Thread(target=wait10seconds) # Create a new thread that exec the function
my_thread.start() # start it
print('test') # print the test
my_thread.join() # wait for the function to end
如果您使用的是 python 3.5+,您可以使用 asyncio:
import asyncio
async def wait10seconds():
for i in range(10):
await asyncio.sleep(1)
return 'Counted to 10!'
print(asyncio.run(wait10seconds()))
asyncio.run
是 python 3.7 的新功能,对于 python 3.5 和 3.6,您将无法使用 asyncio.run
但您可以通过以下方式实现相同的目的直接与 event_loop 合作
您可以使用 Timer。摘自 Python 文档页面:
def hello():
print("hello, world")
t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed