Skip to main content
 首页 » 编程设计

c#之每 5 分钟交替调用两种方法。

2024年02月05日10davidwang456

我想每隔 5 分钟交替调用两个方法,我该怎么做?

public class Program 
{ 
   static void Main(string[] args) 
   { 
      Console.WriteLine(" calling Method1 "); 
      /* After Next 5 minute call Method2 */  
      Console.WriteLine(" calling Method2 "); 
      Console.ReadLine(); 
   }     
   private Method1() 
   { 
     Console.WriteLine("Method1 is executed at {0}", DateTime.Now); 
     Console.ReadLine(); 
   } 
   private Method2() 
   { 
     Console.WriteLine("Method2 is executed at {0}", DateTime.Now); 
     Console.ReadLine(); 
   } 
} 

感谢任何帮助。 谢谢..!

请您参考如下方法:

您可以使用定时器。只需创建一个 Timer 并根据需要的时间构建它。 (1000*5*60) 5分钟。当时间过去时,调用 Timer_Elapsed 方法。使用 bool 值在两种方法之间切换。 提醒: Timer_Elapsed 将在不同的线程上调用。

这是一个例子:

using System.Timers;  // <-- this timer.. Not the Windows.Forms.Timer, because that one works on the messagequeue (to receive the timer_elapsed event on the gui thread), but you don't have a messagequeue/forms 
 
static class Program 
{ 
    private static bool _executeFirstMethod = true; 
 
    static void Main(string[] args) 
    { 
        using (Timer timer = new Timer(5000))  // 5 seconds instead of 5 minutes (for testing) 
        { 
            timer.Elapsed += Timer_Elapsed; 
            timer.Start(); 
            Console.WriteLine("Timer is started"); 
 
            Console.ReadLine(); 
        } 
    } 
 
    private static void Timer_Elapsed(object sender, ElapsedEventArgs e) 
    { 
        if (_executeFirstMethod) 
            Method1(); 
        else 
            Method2(); 
 
        _executeFirstMethod = !_executeFirstMethod; 
    } 
 
    private static void Method1() 
    { 
        Console.WriteLine("Method1 is executed at {0}", DateTime.Now); 
    } 
 
    private static void Method2() 
    { 
        Console.WriteLine("Method2 is executed at {0}", DateTime.Now); 
    } 
} 

结果:

Timer is started 
Method1 is executed at 09-Jun-16 09:49:14 
Method2 is executed at 09-Jun-16 09:49:19 
Method1 is executed at 09-Jun-16 09:49:24 
Method2 is executed at 09-Jun-16 09:49:29 
Method1 is executed at 09-Jun-16 09:49:34 
Method2 is executed at 09-Jun-16 09:49:39