2016-05-12 53 views
2

我试图在没有使用芹菜的特定时间后执行python函数。当requests发生任何异常,然后在60秒后我再次执行相同的功能时,我正在使用requests来访问网址。在没有使用芹菜的特定时间后执行python函数

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

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

+0

但django进入图片的位置?这是纯Python – e4c5

回答

1

您可以在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