Alarm clock application in .Net

2020-01-29 07:09发布

I'm not really writing an alarm clock application, but it will help to illustrate my question.

Let's say that I have a method in my application, and I want this method to be called every hour on the hour (e.g. at 7:00 PM, 8:00 PM, 9:00 PM etc.). I could create a Timer and set its Interval to 3600000, but eventually this would drift out of sync with the system clock. Or I could use a while() loop with Thread.Sleep(n) to periodically check the system time and call the method when the desired time is reached, but I don't like this either (Thread.Sleep(n) is a big code smell for me).

What I'm looking for is some method in .Net that lets me pass in a future DateTime object and a method delegate or event handler, but I haven't been able to find any such thing. I suspect there's a method in the Win32 API that does this, but I haven't been able to find that, either.

7条回答
The star\"
2楼-- · 2020-01-29 07:52

I have used this before with great success:

Vb.net:

Imports System.Threading
Public Class AlarmClock
    Public startTime As Integer = TimeOfDay.Hour
    Public interval As Integer = 1
    Public Event SoundAlarm()
    Public Sub CheckTime()
        While TimeOfDay.Hour < startTime + interval
            Application.DoEvents()
        End While
        RaiseEvent SoundAlarm()
    End Sub
    Public Sub StartClock()
        Dim clockthread As Thread = New Thread(AddressOf CheckTime)
        clockthread.Start()
    End Sub
End Class

C#:

using System.Threading;
public class AlarmClock
{
    public int startTime = TimeOfDay.Hour;
    public int interval = 1;
    public event SoundAlarmEventHandler SoundAlarm;
    public delegate void SoundAlarmEventHandler();
    public void CheckTime()
    {
        while (TimeOfDay.Hour < startTime + interval) {
            Application.DoEvents();
        }
        if (SoundAlarm != null) {
            SoundAlarm();
        }
    }
    public void StartClock()
    {
        Thread clockthread = new Thread(CheckTime);
        clockthread.Start();
    }
}

I don't know if the c# works, but the vb works just fine.

Usage in VB:

Dim clock As New AlarmClock
clock.interval = 1 'Interval is in hours, could easily convert to anything else
clock.StartClock()

Then, just add an event handler for the SoundAlarm event.

查看更多
登录 后发表回答