我可以 运行 python 中的协程独立于所有其他代码吗?

Can I run a coroutine in python independently from all other code?

我有一段代码需要每小时运行。 运行 那段代码 与所有其他代码(这是一个电报机器人)独立 而不必重构所有内容的最佳方法是什么?(现在我知道我可以使用 aiogram为此,但我使用的是不同的库)我正在寻找类似 unity c# coroutine 的东西(你只需 StartCoroutine 并且并行地具有该功能 运行),但是 python 3.9。我一直在寻找不是很复杂的东西,即使这段代码在执行时中断了我的主代码,我也会很高兴,因为它需要大约 1 秒才能完成。

您可以将代码放在一个函数中,然后使用 threading 模块调用它。

from threading import Thread
from time import sleep

# Here is a function that uses the sleep() function. If you called this directly, it would stop the main Python execution
def my_independent_function():
    print("Starting to sleep...")
    sleep(10)
    print("Finished sleeping.")

# Make a new thread which will run this function
t = Thread(target=my_independent_function)
# Start it in parallel
t.start()

# You can see that we can still execute other code, while other function is running
for i in range(5):
    print(i)
    sleep(1)

并且输出:

Starting to sleep...
0
1
2
3
4

Finished sleeping.

如您所见,即使函数正在休眠,主要代码的执行仍在继续。