在C#中每分钟检查一次时间

本文关键字:一次 时间 每分钟 检查 | 更新日期: 2023-09-27 17:57:32

我正在制作一个应用程序,它将每1、5或30分钟甚至每小时通知用户一次。例如,用户在5:06打开程序,程序将在6:06通知用户。

所以我现在的代码是使用Thread.Sleep()函数每5分钟通知一次用户,但我觉得它有点蹩脚。

这是我的代码:

public void timeIdentifier()
    {
        seiyu.SelectVoiceByHints(VoiceGender.Female);
        while(true)
        {
            string alarm = String.Format("Time check");
            seiyu.Speak(alarm);
            string sayTime = String.Format(DateTime.Now.ToString("h:mm tt"));
            seiyu.Speak(sayTime);
            // It will sleep for 5 minutes LOL
            Thread.Sleep(300000);
        }
    }

在C#中每分钟检查一次时间

您可以使用Timers而不是Thread.Sleep():

public class Program
{
    private static System.Timers.Timer aTimer;
    public static void Main()
    {
        aTimer = new System.Timers.Timer(5000); // interval in milliseconds (here - 5 seconds)
        aTimer.Elapsed += new ElapsedEventHandler(ElapsedHandler); // handler - what to do when 5 seconds elaps
        aTimer.Enabled = true;
        // If the timer is declared in a long-running method, use
        // KeepAlive to prevent garbage collection from occurring
        // before the method ends.
        //GC.KeepAlive(aTimer);
    }
    //handler
    private static void ElapsedHandler(object source, ElapsedEventArgs e)
    {
        string alarm = String.Format("Time check");
        seiyu.Speak(alarm);
        string sayTime = String.Format(DateTime.Now.ToString("h:mm tt"));
        seiyu.Speak(sayTime);
    }
}

如果你喜欢更新的.NET TPL语法,你可以这样写:

internal class Program
{
    private static void Main(string[] args)
    {
        Repeat(TimeSpan.FromSeconds(10));
        Console.ReadKey();
    }
    private static void Repeat(TimeSpan period)
    {
        Task.Delay(period)
            .ContinueWith(
                t =>
                {
                    //Do your staff here
                    Console.WriteLine($"Time:{DateTime.Now}");
                    Repeat(period);
                });
    }
}

您可以使用Timer对象(System.Threading)。计时器对象的间隔不是超时。

    static void Main(string[] args)
    {
        int firstCallTimeOut = 0;
        int callInterval = 300000;
        object functionParam = new object();//optional can be null
        Timer timer = new Timer(foo,null,firstCallTimeOut,callInterval);
       
    }
    static void foo(object state)
    {
       //TODO
    }