methuselah
methuselah

Reputation: 13206

Run method several times and delay one by a few seconds

What would be the best way of calling the GenerateRandomBooking() method 5 times and then delaying the GenerateRandomBids() by 2-3 seconds in the while loop below of my console application?

    private static void Main()
    {
        SettingsComponent.LoadSettings();

        while (true)
        {
            try
            {
                    GenerateRandomBooking();
                    GenerateRandomBids();
                    AllocateBids();
                    Thread.Sleep(TimeSpan.FromSeconds(5));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
    }

Upvotes: 0

Views: 112

Answers (2)

Kavindu Dodanduwa
Kavindu Dodanduwa

Reputation: 13059

What about something like this

private static void Main()
{
    SettingsComponent.LoadSettings();

    while (true)
    {
        try
        {
             for(int x=0; x<4 ; x++){
                GenerateRandomBooking(); // Will call 5 times
             }

             Thread.Sleep(2000) // 2 seconds sleep

             GenerateRandomBids();

             AllocateBids();           
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

    }
}

Upvotes: 3

apomene
apomene

Reputation: 14389

using Thread.Sleep() is almost always a bad idea. I believe it is better to use a timer:

 System.Timers.Timer timer = new System.Timers.Timer();

 timer.Interval = 2000;
 timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
 timer.Enabled=false;
 void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)    
{
  timer.Enabled=false;
}  

private static void Main()
{
    SettingsComponent.LoadSettings();

    int counter =0;

    while (true)
    {
        try
        {
             GenerateRandomBooking();
             GenerateRandomBids();
             AllocateBids();
             counter ++;            

             if(counter > 4){
               timer.Enabled=true;
               while (timer.Enabled)
                {
                    ///wait time equal to timer interval...
                }
               counter=0;
             }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

    }
}  

Upvotes: 2

Related Questions