当前位置: 首页 > 编程语言 > C#

如何编写C#调度器分享

时间:2023-04-11 00:07:41 C#

如何编写C#调度器如何编写每天00:00、00:15、00:00等运行的闹钟?你能给我一个示例代码吗?谢谢。您可以使用每分钟运行一次的计时器检查当前时间。检查看起来像:privatevoidOnTimerTick(){if(DateTime.Now.Minutes%15==0){//Dosomething}}但是如果你正在寻找必须每15分钟运行一次的程序或服务,您可以编写应用程序并开始使用Windows计划任务。您可以编写一个程序,在每次打开时执行特定的任务,然后使用Windows计划任务在每天的特定时间执行该程序。你的程序会更简单,你只会专注于你需要实现的逻辑,而安排将由Windows为你免费完成(假设你已经为Windows付费:))。如果你真的想自己实现调度,有这样的框架和库:Quartz.NET如果你想要一个在某个时间间隔执行一些代码的windows服务,你需要创建一个服务项目(见这里),并在这个service使用Timer类(参见此处)。如果要在Windows应用程序执行时运行这些任务,请使用Windows.Forms.Timer,如前所述。.NET中有不同的计时器,根据您要执行的操作(以及在哪个环境中,threadsave,blabla),您应该选择其中之一。更多信息这是一个基础的C#调度程序:usingSystem;使用系统线程;使用System.Windows.Forms;使用System.IO;公共类TimerExample{publicstaticvoidMain(){booljobIsEnabledA=true;booljobIsEnabledB=true;booljobIsEnabledC=true;Console.WriteLine("起始于:{0}",DateTime.Now.ToString("h:mm:ss"));尝试{使用(StreamWriterwriter=File.AppendText("C:\scheduler_log.txt")){while(true){varcurrentTime=DateTime.Now.ToString("h:mm");if(currentTime=="3:15"&&jobIsEnabledA){jobIsEnabledA=false;ThreadPool.QueueUserWorkItem((state)=>{MessageBox.Show(string.Format("该刷牙了!{0}",currentTime));});}if(currentTime=="3:20"&&jobIsEnabledB){jobIsEnabledB=false;ThreadPool.QueueUserWorkItem((state)=>{MessageBox.Show(string.Format("该刷牙了!{0}",currentTime));});}if(currentTime=="3:30"&&jobIsEnabledC){jobIsEnabledC=false;ThreadPool.QueueUserWorkItem((state)=>{MessageBox.Show(string.Format("你最喜欢的节目时间到了!{0}",currentTime));});}if(currentTime=="3:31"){jobIsEnabledA=true;jobIsEnabledB=true;jobIsEnabledC=true;}varlogText=string.Format("{0}jobIsEnabledA:{1}jobIsEnabledB:{2}jobIsEnabledC:{3}",DateTime.Now.ToString("h:mm:ss"),jobIsEnabledA,jobIsEnabledB,jobIsEnabledC);writer.WriteLine(logText);线程.睡眠(1000);}}}catch(Exception异常){Console.WriteLine(exception);}}}例如:以上是C#学习教程:如何编写C#调度器分享的所有内容。如果对你有用,需要进一步了解C#学习教程,希望大家多多关注——usingSystem.Timers;类程序{staticvoidMain(string[]args){Timertimer=newTimer();timer.Interval=newTimeSpan(0,15,0).TotalMilliseconds;timer.AutoReset=true;timer.Elapsed+=newElapsedEventHandler(timer_Elapsed);定时器。启用=真;}staticvoidtimer_Elapsed(objectsender,ElapsedEventArgse){thrownewNotImplementedException();}}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如有转载请注明出处: