irondsd
irondsd

Reputation: 1240

Timer for alarm

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.sstatic.net/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?

Upvotes: 1

Views: 3872

Answers (2)

Brad
Brad

Reputation: 1529

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

Upvotes: 0

Ry-
Ry-

Reputation: 225281

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.

Upvotes: 1

Related Questions