1

I want to make a simple program to make it run in the specific time. Here is my code:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Alarm ft = new Alarm(dateTimePicker1.Value);
    }
}

public class Alarm
{
    public Timer reminder = new Timer();
    public DateTime RemindAt;

    public Alarm(DateTime time)
    {
        RemindAt = time;

        reminder.Interval = (int)(RemindAt - DateTime.Now).TotalMilliseconds;
        reminder.Start();
        reminder.Tick += new EventHandler(reminder_Tick);
    }

    void reminder_Tick(object sender, EventArgs e)
    {
        if (RemindAt <= DateTime.Now)
        {
            reminder.Dispose();
            MessageBox.Show("W: " + RemindAt.ToString("dd MMMM yyyy, HH:mm:ss") + "\n" + "N: " + DateTime.Now.ToString("dd MMMM yyyy, HH:mm:ss") + "\n\n");
        }
    }

As you can seem I use timers, but it seems pretty inaccurate, I have no idea why. Here is the screenshot of 6 alarms: https://i.stack.imgur.com/IGzIh.png

Half of them are wrong. W stands for when it should work, N stands for now. The difference can be huge sometimes, why is that? How to fix that, or maybe there is a better way to make a simple alarm?

irondsd
  • 1,140
  • 1
  • 17
  • 34

2 Answers2

1

System.Windows.Forms.Timers aren't precise, especially for large numbers. Instead of calculating the value for Interval, set it to something constant, say 1000.

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • Yeah, I tried to set timer interval to 1000, but it seems wrong to check it every second. I wanted a better way, so I came up with this code, which doesn't work properly. – irondsd Feb 11 '12 at 09:37
  • @irondsd: Don't worry, once every second won't hurt your processor, even if it does seem a little hackish. (Unless you run it for several weeks, then maybe it does seem a little wrong. But then why aren't you using the Task Scheduler? `taskschd.msc`) – Ry- Feb 11 '12 at 16:38
0

Take a Look at Windows Task Schedular

Basically create your EXE and let Windows handle the time to run.

How to do it via UI

Install it Programmatically

Community
  • 1
  • 1
Brad Semrad
  • 1,501
  • 1
  • 11
  • 19