简体   繁体   English

使用C#在特定时间运行Windows服务任务

[英]Run windows service task at a specific time using C#

i have already design my windows service which include many tasks (same logic run each xxx seconds), but for the new task i have to do : 我已经设计了包含许多任务的Windows服务(每个xxx秒运行相同的逻辑),但是对于新任务,我必须做:

  • Download over HTTP a playlist xml file from a CDN repository in a specific time, let see 03:12:12 pm. 在特定时间通过HTTP从CDN存储库中下载播放列表xml文件,让我们下午03:12:12。

i'am looking for profesional code (just thread or timer squeleton) rather than a code which works. 我正在寻找专业代码(只是线程或计时器squeleton)而不是有效的代码。

I hope i provide you all needed info. 希望我能为您提供所有需要的信息。

Best regards 最好的祝福

Bratom Bratom

如果您需要一个调度库,我会推荐Quartz.Net ,我在不同项目中使用了Quartz.Net ,效果很好。

I know you're looking for code, but when we need daily tasks to be done with our services, we construct the service and leave the execution of it up to the operating system. 我知道您正在寻找代码,但是当我们需要使用我们的服务完成日常任务时,我们将构建服务并将其执行工作交给操作系统。

Schedule tasks 安排任务

Just throw a line of code in a .bat file that starts the service and schedule that batch file to run at certain times. 只需在.bat文件中放入一行代码即可启动该服务,并安排该批处理文件在特定时间运行。

Doing something at a specific time is not much different from doing it periodically. 在特定时间执行某项操作与定期执行并没有太大区别。

Let's say you want to do something at some point in the future. 假设您想在将来的某个时候做某事。 We'll call that targetDate . 我们将其称为targetDate

DateTime targetDate = GetActionTime(); // whatever

// compute the difference between targetDate and now.
// we use UTC so that automatic time changes (like daylight savings) don't affect it
TimeSpan delayTime = targetDate.ToUniversalTime() - DateTime.UtcNow;

// Now create a timer that waits that long ...
Timer t = new Timer(TimerProc, null, delayTime, TimeSpan.FromMilliseconds(-1));

That timer will trigger the callback once. 该计时器将触发一次回调。 If you want that to repeat at the same time every day, you can pass the target date (or perhaps a reference to the record that describes the whole event) to the timer proc, and have the timer proc update the target date and then call Timer.Change to change the timer's due time. 如果您希望每天在同一时间重复该操作,则可以将目标日期(或对描述整个事件的记录的引用)传递给计时器proc,并让计时器proc更新目标日期,然后调用Timer.Change更改计时器的到期时间。 Be sure to set the period to -1 milliseconds in order to prevent it from becoming a periodic timer. 确保将时间段设置为-1毫秒,以防止其成为定期计时器。

您需要使用C#实现Cron的实现,请尝试以下一种方法: http : //www.raboof.com/Projects/NCrontab/http://sourceforge.net/projects/cronnet/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM