[英]Creating a C# service to monitor changes in infinite loop
我的目标是查看Time1和Time2之间是否有任何变化。 如果有更改,我需要发送电子邮件并跳过其余检查,然后在另一个时间间隔内进行另一次更改。
这是我第一次创建服务,所以这是我做的:
protected override void OnStart(string[] args)
{
DateTime lastUpdate = new DateTime();
lastUpdate = new DateTime(2014, 01, 01, 00, 00, 00);
DateTime curTime = new DateTime();
bool infLoop = true;
while (infLoop)
{
curTime = DateTime.Now;
//define time range1
DateTime startDateMorning = new DateTime(curTime.Year, curTime.Month, curTime.Day, 17, 40, 00);
DateTime endDateMorning = new DateTime(curTime.Year, curTime.Month, curTime.Day, 17, 50, 00);
//define time range2
DateTime startDateEvening = new DateTime(curTime.Year, curTime.Month, curTime.Day, 10, 30, 00);
DateTime endDateEvening = new DateTime(curTime.Year, curTime.Month, curTime.Day, 10, 40, 00);
//time span between last update and current time in iteration
TimeSpan span = curTime - lastUpdate;
//check that we only monitor within interwals, and there was at least 20 minutes delay between last and current check
if (((curTime >= startDateMorning && curTime < endDateMorning)
||
(curTime >= startDateEvening && curTime < endDateEvening))
&& span.Minutes > 20)
{
//connect to DataBase
//get the value
//email warning
//other logic
//set last uopdate as current timestamp
lastUpdate = DateTime.Now;
}
}
}
当我使用sc create Service1 start= auto binPath= "c:\\Users\\....\\program.exe"
并尝试运行它时,我的服务卡住了。 因此,我必须寻找它并手动终止它。 我认为我做错了。
您需要使用Thread.Sleep()
避免繁忙的等待,或者更好的是,仅在需要时使用System.Timers.Timer
(或其表亲之一)唤醒。 您还需要在OnStart()
启动服务,而不是尝试在那里进行所有服务。 这意味着调度事件处理程序(例如,通过Timer
)或启动新线程,以便OnStart()
可以在其原始线程上返回。 Windows Service系统仅提供有限的启动时间。 还需要实现OnStop()
才能正常关闭。
public partial class ServiceClassName : ServiceBase {
private readonly Timer Ticker = new Timer {
Interval = 5.0*TimeSpan.TicksPerMinute
/TimeSpan.TicksPerMillisecond
}; // 5 minutes
public ServiceClassName() {
InitializeComponent();
Ticker.Elapsed += (sender, e) => Poll();
}
protected override void OnStart(string[] args) { Ticker.Start(); }
protected override void OnStop() { Ticker.Stop(); }
internal static void Poll() {
// approximate contents of your while loop
}
}
“我的服务被卡住”不是太具描述性,但是您需要尽快从OnStart返回。 您还需要响应其他服务命令(例如OnStop),该代码无法响应,因为它陷入了循环。
在单独的线程中运行代码,例如使用Task
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.