2017-05-31 128 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

您可以使用另一个计时器在一小时后停止第一个计时器。我更新了答案。 –

相关问题