2016-08-25 142 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

難道沒有人爲此付出時間嗎? –