如何编写C#Scheduler

如何编写将在每天00:00,00:15,00:00等运行的警报?

你能给我一个示例代码吗?

谢谢。

您可以使用每分钟运行一次的计时器来检查当前时间。 支票看起来像:

private void OnTimerTick() { if(DateTime.Now.Minutes%15==0) { //Do something } } 

但是,如果您正在寻找必须每15分钟运行一次的程序或服务,您可以编写应用程序并开始使用Windows计划任务。

您可以编写程序以在每次打开时执行特定任务,然后在特定时间每天使用Windows计划任务执行程序。

您的程序将更简单,您将只关注您需要实现的逻辑,安排将由Windows为您完成,免费(假设您已经支付Windows :))。

如果你真的想自己实现调度,那么就有这样的框架和库: Quartz.NET

如果你想要一些时间间隔执行某些代码的windows服务,你需要创建服务项目(见这里 ),并在这个服务中使用Timer类(见这里 )。 如果要在执行Windows应用程序时运行这些任务,请使用Windows.Forms.Timer,如前所述。

.NET中有不同的计时器

  • System.Threading.Timer
  • System.Windows.Forms.Timer
  • System.Timers.Timer

根据你想要做的事情(以及在哪个环境,threadsave,bla bla)你应该选择其中一个。

更多信息

这是一个基本的C#调度程序:

 using System; using System.Threading; using System.Windows.Forms; using System.IO; public class TimerExample { public static void Main() { bool jobIsEnabledA = true; bool jobIsEnabledB = true; bool jobIsEnabledC = true; Console.WriteLine("Starting at: {0}", DateTime.Now.ToString("h:mm:ss")); try { using (StreamWriter writer = File.AppendText("C:\\scheduler_log.txt")) { while (true) { var currentTime = DateTime.Now.ToString("h:mm"); if (currentTime == "3:15" && jobIsEnabledA) { jobIsEnabledA = false; ThreadPool.QueueUserWorkItem((state) => { MessageBox.Show(string.Format("Time to brush your teeth! {0}", currentTime) ); }); } if (currentTime == "3:20" && jobIsEnabledB) { jobIsEnabledB = false; ThreadPool.QueueUserWorkItem((state) => { MessageBox.Show(string.Format("Time to brush your teeth! {0}", currentTime)); }); } if (currentTime == "3:30" && jobIsEnabledC) { jobIsEnabledC = false; ThreadPool.QueueUserWorkItem((state) => { MessageBox.Show(string.Format("Time for your favorite show! {0}", currentTime)); }); } if (currentTime == "3:31") { jobIsEnabledA = true; jobIsEnabledB = true; jobIsEnabledC = true; } var logText = string.Format("{0} jobIsEnabledA: {1} jobIsEnabledB: {2} jobIsEnabledC: {3}", DateTime.Now.ToString("h:mm:ss"), jobIsEnabledA, jobIsEnabledB, jobIsEnabledC); writer.WriteLine(logText); Thread.Sleep(1000); } } } catch (Exception exception) { Console.WriteLine(exception); } } } 

例如:

 using System.Timers; class Program { static void Main(string[] args) { Timer timer = new Timer(); timer.Interval = new TimeSpan(0, 15, 0).TotalMilliseconds; timer.AutoReset = true; timer.Elapsed += new ElapsedEventHandler(timer_Elapsed); timer.Enabled = true; } static void timer_Elapsed(object sender, ElapsedEventArgs e) { throw new NotImplementedException(); } }