每隔5分钟交替调用两种方法。

时间:2016-06-08 08:16:22

标签: c#

我想每隔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();
   }
}

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

2 个答案:

答案 0 :(得分:3)

您可以使用计时器。只需创建一个Timer并根据需要构建它。 (1000 * 5 * 60)持续5分钟。经过时间后,将调用Timer_Elapsed方法。使用布尔值在两个方法之间切换。 提醒: 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

答案 1 :(得分:1)

如果您的程序遵循问题的基本结构,那么您甚至不需要计时器,只需Thread.Sleep

public class Program
{
   static void Main(string[] args)
   {
      while(true)
      {
        Method1();
        System.Threading.Thread.Sleep(TimeSpan.FromMinutes(5));

        Method2();
        System.Threading.Thread.Sleep(TimeSpan.FromMinutes(5));
      }
   }    
   private Method1()
   {
     Console.WriteLine("Method1 is executed at {0}", DateTime.Now);
   }
   private Method2()
   {
     Console.WriteLine("Method2 is executed at {0}", DateTime.Now);
   }
}