I am trying to execute a python function after specific time without using celery. I'm hitting a url using requests
when requests
raises any exception then after 60 seconds I execute same function again.
我尝试在不使用芹菜的特定时间后执行python函数。当请求引发任何异常时,我使用请求点击url,然后在60秒后再次执行相同的函数。
def myfun():
try:
response = requests.post('url', data=data)
except Exception as e:
sleep(60)
myfun()
But this is recursive function and will consume memory. I want to write an async function to execute my task. How can this be done?
但这是递归函数,会消耗内存。我想编写一个异步函数来执行我的任务。怎么做呢?
1 个解决方案
#1
1
You can use ayncronous tasks in python multiprocessing. Here is an example
您可以在python多处理中使用ayncriness任务。这是一个例子
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
Read full documentation here.
阅读完整的文档。
#1
1
You can use ayncronous tasks in python multiprocessing. Here is an example
您可以在python多处理中使用ayncriness任务。这是一个例子
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
Read full documentation here.
阅读完整的文档。