2017-05-31 61 views
0

我有一個C#控制檯應用程序。我想每分鐘執行一次功能,最多1小時。該函數返回一個布爾值。如果該函數返回true,則定時器應該停止,否則應該每分鐘執行一次,最多1小時。 以下是我迄今爲止編寫的代碼。定期執行一個函數,如果返回true則停止

static void Main(string[] args) 
{ 
    var timer = new System.Timers.Timer(60000); 
    timer.Elapsed += new 
    System.Timers.ElapsedEventHandler(CheckEndProcessStatus); 
    //if timer timed out, stop executing the function 
} 

private void CheckEndProcessStatus(object source, ElapsedEventArgs args) 
{ 
    try 
    { 
     if (CheckFunction()) 
     { 
      //stop timer 
     } 
    } 
    catch(Exception ex) 
    { 
     throw; 
    } 
} 

private bool CheckFunction() 
{ 
    bool check = false; 

    try 
    { 
     //some logic to set 'check' to true or false 
    } 
    catch (Exception ex) 
    { 
     throw; 
    } 
    return check; 
} 

我想我需要一些指導來實現這個。請讓我知道我是否可以提供更多細節。

+1

*代碼不完整*您是怎麼想的?你需要實現 –

+0

如果只是這個簡單的應用程序,你可以嘗試使用'while(true)'然後'Thread.Sleep(60000)'(1分鐘)而不是定時器,那麼你可以簡單地跳出通過返回一個'false'布爾值來循環。但是,這會鎖定主線程,所以如果項目比您在此處顯示的項目大,我不會建議使用它。更多信息:https://stackoverflow.com/questions/8815895/why-is-thread-sleep-so-harmful –

+0

@ChristopherLake是的,我現在正在做。但是,如你所知,這不是一個好方法。 –

回答

2

只需調用timer.stop()即可停止定時器。它在內部呼叫timer.Enabled = false 使用另一個定時器在一小時後停止第一個定時器。

private static Timer timer; 
    private static Timer oneHourTimer; 

    static void Main(string[] args) 
    { 
     oneHourTimer = new System.Timers.Timer(3600 * 1000); 
     timer = new System.Timers.Timer(60 * 1000); 

     timer.Elapsed += new System.Timers.ElapsedEventHandler(CheckEndProcessStatus); 
     oneHourTimer.Elapsed += oneHourTimer_Elapsed; 

     oneHourTimer.Start(); 
     timer.Start(); 
    } 

    static void oneHourTimer_Elapsed(object sender, ElapsedEventArgs e) 
    { 
     timer.Stop(); 
     //maybe stop one hour timer as well here 
     oneHourTimer.Stop(); 
    } 

    private static void CheckEndProcessStatus(object source, ElapsedEventArgs args) 
    { 
     try 
     { 
      if (CheckFunction()) 
      { 
       //stop timer 
       timer.Stop(); 
      } 
     } 
     catch (Exception ex) 
     { 
      throw; 
     } 
    } 

    private static bool CheckFunction() 
    { 
     bool check = false; 

     try 
     { 
      //some logic to set 'check' to true or false 
     } 
     catch (Exception ex) 
     { 
      throw; 
     } 
     return check; 
    } 
+0

我該如何配置它以1分鐘的間隔運行1小時? –

+1

您可以使用另一個計時器在一小時後停止第一個計時器。我更新了答案。 –

相關問題