Skip to main content
 首页 » 编程设计

c#之创建一个 C# 服务来监视无限循环中的变化

2024年02月06日21birdshome

我的目标是查看 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 服务系统只提供有限的启动时间。 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 
    } 
}