Search code examples
c#timeclockalarmprocessor

How to reduce the processor consumption?


I have made a C# alarm clock and it's working fine. the problem is that when it runs it consumes 20% of the processor (on an i5 2410M processor) what should I do? here is my code:

using System;
namespace assigment1
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime uptime = new DateTime (2013,12,10,4,0,0);
            Console.WriteLine("This alarm is set to go off at 4:00 am");
            while (true)
            {

                if (DateTime.Now.Minute == uptime.Minute && DateTime.Now.Hour == uptime.Hour)
                {
                    for (int j = 1000; j < 22767; j++)
                     {


                        Console.Beep(j, 500);
                        Console.Write("Wake up! it is {0}:{1} already! ", DateTime.Now.Hour, DateTime.Now.Minute);
                     }

                }
             }
        }
    }
}

Solution

  • You need to calculate the time till till the alarm should beep and use the timer class. Just set the interval to the time remaining till alarm and stop the timer after that. Something like this should work

    DateTime alarmTime = new DateTime(2013,12,10,4,0,0);
    System.Windows.Forms.Timer alarmTimer = new System.Windows.Forms.Timer();
    alarmTimer.Interval = (alarmTime - DateTime.Now).Milliseconds;
    alarmTimer.Tick += alarmTimer_Tick;
    alarmTimer.Start();
    

    your event

    void alarmTimer_Tick(object sender, EventArgs e)
    {
        alarmTimer.Stop();
        Console.Write("Wake up! it is {0}:{1} already! ", DateTime.Now.Hour, DateTime.Now.Minute);
    }