2016-08-25 143 views
0

我刚刚创建了一个脚本,该脚本从特定的API触发报告,然后将其加载到我的数据库中。 我已经构建了一些可行的工具,但是我想知道是否有更多“精确”或高效的东西,而不需要一遍又一遍地重复我的脚本循环。等待没有循环的条件Python

我当前的脚本如下:

import time 

retry=1 
trigger_report(report_id) 

while report_id.status() != 'Complete': 
    time.sleep(retry * 1.3) 
    retry =+ 1 

load_report(report_id) 

编辑:

不与任何等待完成方法提供的API,它具有最是返回状态的端点的工作。 它是一个SOAP API。

+0

检查API的“等待完成”方法或回调或somesuch。也许你甚至可以以阻塞的方式调用你想要使用的功能,直到完成。 – Hurkyl

+3

除非您使用的API提供了更好的方法,否则。没有关于API的细节,这基本上是我们可以告诉你的。 –

回答

0

尽管这篇文章不再像你所说的那样具有任何相关性,但它是一个soap API。但是我把工作放到了它里面,所以我会把它贴出来。 :)

要回答你的问题。我没有看到比轮询更有效的方法(又称。循环一遍又一遍)


有多种方法可以做到这一点。

第一种方法是实现任务完成时触发的某种回调。它会是这个样子:

import time 

def expensive_operation(callback): 
    time.sleep(20) 
    callback(6) 

expensive_operation(lambda x:print("Done", x)) 

正如你所看到的,消息“Done 6”将尽快操作已经完成打印。

你可以用Future对象重写这个。

from concurrent.futures import Future 
import threading 
import time 

def expensive_operation_impl(): 
    time.sleep(20) 
    return 6 

def expensive_operation(): 
    fut = Future() 
    def _op_wrapper(): 
     try: 
      result = expensive_operation_impl() 
     except Exception as e: 
      fut.set_exception(e) 
     else: 
      fut.set_result(result) 

    thr = threading.Thread(target=_op_wrapper) 
    thr.start() 

    return fut 

future = expensive_operation() 
print(future.result())    # Will block until the operation is done. 

由于这看起来很复杂,所以有一些高级函数为你实现线程调度。

import concurrent.futures import ThreadPoolExecutor 
import time 

def expensive_operation(): 
    time.sleep(20) 
    return 6 

executor = ThreadPoolExecutor(1) 
future = executor.submit(expensive_operation) 

print(future.result()) 
-3

而不是使用事件,而不是轮询。有很多关于如何在Python中实现事件的选项。有一个讨论here already on stack overflow

这是一种人工合成的示例使用zope.event和事件处理程序

import zope.event 
import time 


def trigger_report(report_id): 
    #do expensive operation like SOAP call 
    print('start expensive operation') 
    time.sleep(5) 
    print('5 seconds later...') 
    zope.event.notify('Success') #triggers 'replied' function 

def replied(event): #this is the event handler 
    #event contains the text 'Success' 
    print(event) 

def calling_function(): 
    zope.event.subscribers.append(replied) 
    trigger_report('1') 

但期货作为公认的答案也整齐。取决于什么漂浮你的船。

+2

要成为写作问题的答案,您必须解释如何在不控制通常会触发事件的代码部分时使用事件。 – Hurkyl

+0

难道没有人为此付出时间吗? –