Count the elapsed time only after finishing the current iteration before going to the new iteration

StackOverflow https://stackoverflow.com/questions/22584067

  •  19-06-2023
  •  | 
  •  

Question

I was trying to make a timer that would run a code each 5 seconds. But these 5 seconds could only be counted after the current code finishes to run.

Example:

static void Main(string[] args)
{
    System.Timers.Timer timer = new System.Timers.Timer(5000);

    timer.Elapsed += (obj, ev) =>
    {
        System.IO.File.AppendAllLines(@"D:\test.txt", new string[] { DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") }, Encoding.UTF8);
        System.Threading.Thread.Sleep(3000);

        System.IO.File.AppendAllLines(@"D:\test.txt", new string[] { DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") + " - New" }, Encoding.UTF8);
    };

    timer.Start();

    Console.ReadLine();
}

Result:

22/03/2014 06:39:36
22/03/2014 06:39:39 - New
22/03/2014 06:39:41
22/03/2014 06:39:44 - New
22/03/2014 06:39:46
22/03/2014 06:39:49 - New
22/03/2014 06:39:51
22/03/2014 06:39:54 - New
22/03/2014 06:39:56
22/03/2014 06:39:59 - New
22/03/2014 06:40:01
22/03/2014 06:40:04 - New
22/03/2014 06:40:06

Expected result:

22/03/2014 06:39:36
22/03/2014 06:39:39 - New
22/03/2014 06:39:44
22/03/2014 06:39:47 - New
22/03/2014 06:39:52
22/03/2014 06:39:55 - New
22/03/2014 06:40:00
22/03/2014 06:40:03 - New
22/03/2014 06:40:08
22/03/2014 06:40:11 - New
22/03/2014 06:40:16
22/03/2014 06:40:19 - New
22/03/2014 06:40:24

Is there any way to count the elapsed time only after the current event is finished?

One important thing: The only class I can use for this is System.Timer.Timer, and I cannot use Thread.Sleep, or any kind of recursive method.

Thanks, and I appreciate your answers =)

Was it helpful?

Solution

Maybe the AutoReset property can help.

static void Main(string[] args)
{
    System.Timers.Timer timer = new System.Timers.Timer(5000);

    timer.Elapsed += (obj, ev) =>
    {
        System.IO.File.AppendAllLines(@"D:\test.txt", new string[] { DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") }, Encoding.UTF8);
        System.Threading.Thread.Sleep(3000);

        System.IO.File.AppendAllLines(@"D:\test.txt", new string[] { DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") + " - New" }, Encoding.UTF8);

        //if you want to be sure it will execute, wrap the code above with try... catch
        timer.Start();
    };
    timer.AutoReset = false;
    timer.Start();

    Console.ReadLine();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top