我正在制作一个应用程序,每 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);
}
}
最佳答案
您可以使用定时器代替 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);
}
}
关于c# - 在 C# 中检查每分钟的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38454349/