gpt4 book ai didi

python - 在不使用 celery 的情况下在特定时间后执行python函数

转载 作者:太空宇宙 更新时间:2023-11-04 05:30:52 25 4
gpt4 key购买 nike

我想在不使用 celery 的情况下在特定时间后执行 python 函数。当 requests 引发任何异常时,我正在使用 requests 访问一个 url,然后在 60 秒后我再次执行相同的功能。

def myfun():
try:
response = requests.post('url', data=data)
except Exception as e:
sleep(60)
myfun()

但是这是递归函数,会消耗内存。我想编写一个异步函数来执行我的任务。如何做到这一点?

最佳答案

您可以在 python 多处理中使用异步任务。这是一个例子

from multiprocessing import Pool
import time

def f(x):
return x*x

if __name__ == '__main__':
pool = Pool(processes=4) # start 4 worker processes

result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously in a single process
print result.get(timeout=1) # prints "100" unless your computer is *very* slow

print pool.map(f, range(10)) # prints "[0, 1, 4,..., 81]"

it = pool.imap(f, range(10))
print it.next() # prints "0"
print it.next() # prints "1"
print it.next(timeout=1) # prints "4" unless your computer is *very* slow

result = pool.apply_async(time.sleep, (10,))
print result.get(timeout=1) # raises multiprocessing.TimeoutError

阅读完整文档 here .

关于python - 在不使用 celery 的情况下在特定时间后执行python函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37184015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com