2016-04-02 4 views
0

私はちょうどこのような何かを探していた。私のC#バージョンに似た、エレガントなPythonの再利用可能な待機がありますか?

public static class Retry 
{ 
    public static void Do(
     Action action, 
     TimeSpan retryInterval, 
     int retryCount = 3) 
    { 
     Do<object>(() => 
     { 
      action(); 
      return null; 
     }, retryInterval, retryCount); 
    } 

    public static T Do<T>(
     Func<T> action, 
     TimeSpan retryInterval, 
     int retryCount = 3) 
    { 
     var exceptions = new List<Exception>(); 

     for (int retry = 0; retry < retryCount; retry++) 
     { 
      try 
      { 
       if (retry > 0) 
        Thread.Sleep(retryInterval); 
       return action(); 
      } 
      catch (Exception ex) 
      { 
       exceptions.Add(ex); 
      } 
     } 

     throw new AggregateException(exceptions); 
    } 
} 

このポストから:Cleanest way to write retry logic?

私は誰かがいくつかのヒントを持っている場合、これは本当にいいかもしれないことを知ってPythonで十分まともです。これは非常に頻繁に起こりますが、優雅に処理されることはめったにありません。

+1

この[**再試行**](https://pypi.python.org/pypi/再試行/)パッケージがあなたの望むものかもしれません。 – Anzel

答えて

0

あなたがしてくださいますよう例外処理や他の添えものを追加し、このような何かを行うことができます。

def retry_fn(retry_count, delay, fn, *args, *kwargs): 
    retry = True 
    while retry and retry_count: 
     retry_count -= 1 
     success, results = fn(*args, **kwargs): 
     if success or not retry_count: 
      return results 
     time.sleep(delay) 
関連する問題