2012-03-14 147 views
-1

我有一个循环,根据某些条件连续运行一个函数。 现在,我只想在循环内每10分钟调用一次该函数。 我使用Visual Studio 2005中我的代码是:如何在循环中使用c#每10分钟运行一次函数?

while (boolValue == false) 
    { 
     Application.DoEvents(); 
     StartAction(); //i want to call this function for every 10 minutes only 
    } 

我现在用的是System.Timers,但它不是调用函数。我不知道什么是错的。

我的代码是:

public static System.Timers.Timer aTimer; 
    while (boolValue == false) 
    { 
     aTimer = new System.Timers.Timer(50000); 
     aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); 
     aTimer.AutoReset = false; 
     aTimer.Enabled = true; 
    } 

    private static void OnTimedEvent(object source, ElapsedEventArgs e) 
    { 
     Application.DoEvents(); 
     StartAction(); 
    } 
+0

尝试Quartz.net作业调度程序。 http://stackoverflow.com/questions/8633662/call-a-method-at-a-certain-time 这是一个开源的 – Anand 2012-03-14 04:10:15

+0

'aTimer.AutoReset = FALSE;如果你想'有你的问题 – Yaur 2012-03-14 04:31:04

+0

无限期地执行此操作(即使在应用程序关闭后),可以考虑编写一个应用程序来执行一次 - 即使是控制台应用程序。然后在Windows中添加一个计划任务,每10分钟运行一次。 – 2012-03-28 14:39:32

回答

5

为什么不直接使用timer。每隔十分钟触发一次。

在更具体的版本example是一个很好的例子其实

UPDATE

在你更新的代码,我会把它改成这样:

public static System.Timers.Timer aTimer; 
... 
aTimer = new System.Timers.Timer(50000); 
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); 
aTimer.AutoReset = false; //This should be true if you want it actually looping 
aTimer.Enabled = true; 

我不看到一个理由有一个while循环。我的猜测是while循环根本没有被触发。此外,您应该将AutoReset设置为true,以便连续运行。

相关问题