我正在尝试使闹钟在特定时间响(例如,上午9:30至下午4点后每五分钟一次)。因此,我想编写一个在9:30和9:35以及...响起的代码。但最终,每种方法我都会出错。在我的代码中,我有一个包含时间的字符串,但是我不能在if(...)中使用该字符串或组来发出警报。只需使用var一个数字就可以了...,我在哪里错了?
public partial class Form1 : Form
{
//default constructor
public static List<Recipe> RecipeList = new List<Recipe>();
}
public partial class Form2
{
//default constructor
private void Form2_Load(object sender, Eventargs e)
{
RecipeList.Add("Chili con Carne");
}
}
public class Recipe
{
//some properties and methods...
{
答案 0 :(得分:0)
private void Form1_Load(object sender, EventArgs e)
{
timer = new System.Timers.Timer();
timer.Interval = 1000 * 60 * 5; //5 minutes
timer.Elapsed += Timer_Elapsed;
InitializeTimer(); //this method makes sure the timer starts at the correct time
}
计时器初始化方法:
private async void InitializeTimer()
{
while (!timer.Enabled) //keep looping until timer is initialized
{
//if the minute is a multiple of 5 (:00, :05, ...) start the timer
if (DateTime.Now.Minute % 5 == 0 && DateTime.Now.Second == 0)
{
timer.Start();
TriggerAlarm(); //trigger the alarm initially instead of having to wait 5min
}
else
{
await Task.Delay(100);
}
}
}
您可以将时间和警报路径存储在字典中:
Dictionary<TimeSpan, string> dict = new Dictionary<TimeSpan, string>()
{
{ new TimeSpan(9, 30, 0), @"C:\Windows\Media\Time interval alarm\FiveH.wav" },
{ new TimeSpan(9, 35, 0), @"C:\Windows\Media\Time interval alarm\Whatever.wav" },
{ new TimeSpan(9, 40, 0), @"C:\Windows\Media\Time interval alarm\Whatever1.wav" },
{ new TimeSpan(9, 45, 0), @"C:\Windows\Media\Time interval alarm\Whatever2.wav" },
//...
{ new TimeSpan(16, 0, 0), @"C:\Windows\Media\Time interval alarm\Whatever3.wav" }
};
Timer_Elapsed事件,自警报启动以来每5分钟触发一次
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
TriggerAlarm();
}
播放声音的方法
private static void TriggerAlarm()
{
TimeSpan alarmTime = new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, 0);
if (dict.TryGetValue(alarmTime, out string alarmFile))
{
using (SoundPlayer player = new SoundPlayer(alarmFile))
{
player.Play();
}
}
else
{
//this alarm time is not found in the dictionary,
//therefore, no alarm should be played at this time (e.g. 16:05:00)
}
}