Reputation: 841
I want to periodically check for 60 s in C#. I was able to do it by checking the date periodically as follows
However, when I use the stopwatch, the stopwatch resets back to the beginning instead of continuing from the previous time the stopwatch was stopped.
using System;
using System.Diagnostics;
using System.Threading;
namespace StopwatchExample
{
class Program
{
static void Main()
{
////Works
//DateTime start = DateTime.Now;
//while (true)
//{
// DateTime current = DateTime.Now;
// var diffInSeconds = (current - start).TotalSeconds;
// if (diffInSeconds > 5)
// {
// Console.WriteLine("5 s done!");
// break;
// }
//}
// Does not work
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
while (true)
{
stopwatch.Stop();
if (stopwatch.Elapsed.Seconds > 5)
{
Console.WriteLine("5 s done!");
break;
}
else
{
stopwatch.Start();
}
}
Console.ReadLine();
}
}
}
Upvotes: 0
Views: 4677
Reputation: 49300
As others have said, a Timer
is probably the better solution. Given your usage of Stopwatch
, you need to change your logic to this:
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
while (true)
{
// Check elapsed time w/o stopping/resetting the stopwatch
// May want to include the 5 seconds themselves (>= instead of >)
if (stopwatch.Elapsed.Seconds >= 5)
{
// At least 5 seconds elapsed, restart stopwatch.
stopwatch.Stop();
stopwatch.Start();
Console.WriteLine("5 s done!");
// Not sure about this, if you really want to check "periodically",
// this break makes less sense, because the checking
// logic will stop after the first 5 seconds have elapsed.
break;
}
}
Upvotes: 2
Reputation: 118
Try to use Timer (System.Timers) instead of Stopwatch. Set the required interval and perform the necessary actions on Elapsed event.
Here you can find out more.
Example:
public static void Main()
{
// Create a timer and set a two second interval.
aTimer = new System.Timers.Timer();
aTimer.Interval = 2000; // 2000ms == 2s
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
// Have the timer fire repeated events (true is the default)
aTimer.AutoReset = true;
// Start the timer
aTimer.Enabled = true;
Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine();
}
private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
Console.WriteLine("The interval has been elapsed");
}
Upvotes: 6