1

i want to check if the current time is a specific time so for example if the current time is 13:13:13 it would beep

var xx = new DateTime(2018,10,8,13,19,50);

while (true)
{
    if (DateTime.Now == xx)
        Console.Beep();
}

but it is not working

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
crystals
  • 45
  • 7

4 Answers4

3

Give your CPU a break.

static void Main(string[] args)
{
    var target = DateTime.Now.AddMinutes(1);  // test data

    var aTimer = new System.Timers.Timer((target - DateTime.Now).TotalMilliseconds);
    aTimer.Elapsed += (s, e) => { Console.Beep(); };
    aTimer.Enabled = true;

    Console.WriteLine("Wait a minute...");
    // time to do something useful
    Console.ReadLine();
}
bommelding
  • 2,969
  • 9
  • 14
  • Do not forget to `Dispose` the `Timer` instance: `aTimer.Elapsed += (s, ee) => {(s as System.Timers.Timer)?.Dispose(); Console.Beep(); };` – Dmitry Bychenko Oct 08 '18 at 12:45
  • Yes, a using block would have been the better practice. Although I don't think this Timer really needs it, it's more a formality form its base class. And we are at the end of Main anyway. – bommelding Oct 08 '18 at 12:53
1

When checking for == you actually compare ticks: if

 DateTime.Now == 2018-10-18 13:19:50.0000000

and thus there's only a tiny probability to go off Beep:

 ...
 DateTime.Now == 2018-10-18 13:19:49.9999852
 DateTime.Now == 2018-10-18 13:19:49.9999989 // Transition: no beep here
 DateTime.Now == 2018-10-18 13:19:50.0000007 // infinte loop from now on
 ...

Try different test (quick patch; Timer is a better solution):

    var xx = new DateTime(2018,10,8,13,19,50);

    while (true)
    {
        // If DateTime.Now exceeds xx 
        if (DateTime.Now >= xx) {
            // bee..eep
            Console.Beep();

            // and break the loop  
            break;
        }
    }
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

Time can be divided into really, really small fractions. You need to decide the resolution of time you're okay with. Should it beep if it is the same time down to the second? Or should it be the same time down to the millisecond? Or the nanosecond?

Once you've decided on this, you need to declare your xx value down to that precision, and in the loop, truncate DateTime.Now to the required precision. Then your comparison will do what you want.

Bas
  • 1,946
  • 21
  • 38
0

There are many approaches.

  • You could use the task scheduler Creating Scheduled Tasks
  • or could use Quartz.Net Cron with Quartz
  • or just make a sleep:

    var xx = new DateTime(2018,10,8,13,19,50);

    System.Threading.Thread.Sleep(new TimeSpan(xx - DateTime.Now).TotalMilliseconds);

    Console.Beep();

owairc
  • 1,890
  • 1
  • 10
  • 9