C# – 具有系统时间意识的Windows服务

我正在考虑编写一个Windows服务,它将在用户指定的时间打开或关闭某个function(使用我将提供的配置实用程序)。 基本上,用户将指定PC将进入“仅工作”模式(阻止Facebook和其他分散注意力的站点)的某些时间,然后当这些时间到来时,PC将返回到正常模式。

我已经提出了一些方法来创建“仅限工作”模式,但我正在努力的是如何知道何时进出该模式。 如果我可以避免它,我真的不想使用线程和计时器,因为这似乎会产生大量的开销,所以我正在寻找的方法是:

  • 如果要检查某种timeChanged()事件,请进入Windows API
  • 使用某种预先构建的库在指定时间触发事件
  • 我没有想到的其他一些方法是优雅和美妙的

有谁知道这样做的最佳方法?

我认为如前所述,使用Windows服务可以很好地实现它。 在我们的一个制作系统中,我们有一个以下面的方式实现的Windows服务(不同的核心function),现在已经安全运行了近三年。

基本上,以下代码的目的是每次内部计时器( myTimer )唤醒时服务执行某些方法。

以下是基本实现。 在此示例中,您的核心function应放在EvalutateChangeConditions方法中,该方法应该每60秒执行一次。 我还将为您的管理客户提供一种公共方法,以了解当前的“工作模式”。

 public partial class MyService : ServiceBase { private System.Threading.Thread myWorkingThread; private System.Timers.Timer myTimer = new System.Timers.Timer(); // [...] Constructor, etc protected override void OnStart(string[] args) { // Do other initialization stuff... // Create the thread and tell it what is to be executed. myWorkingThread = new System.Threading.Thread(PrepareTask); // Start the thread. myWorkingThread.Start(); } // Prepares the timer, sets the execution interval and starts it. private void PrepareTask() { // Set the appropiate handling method. myTimer.Elapsed += new System.Timers.ElapsedEventHandler(myTimer_Elapsed); // Set the interval time in millis. Eg: each 60 secs. myTimer.Interval = 60000; // Start the timer myTimer.Start(); // Suspend the thread until it is finalised at the end of the life of this win-service. System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite); } void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { // Get the date and time and check it agains the previous variable value to know if // the time to change the "Mode" has come. // If does, do change the mode... EvalutateChangeConditions(); } // Core method. Get the current time, and evaluate if it is time to change void EvalutateChangeConditions() { // Retrieve the config., might be from db? config file? and // set mode accordingly. } protected override void OnStop() { // Cleaning stuff... } } 

如果Windows任务计划程序没有理由不适合您,我建议您使用它。

如果你不想使用任务调度程序,我会有一个简单的循环来检查任何即将发生的事件(锁定/解锁站点)并执行任何到期事件。 如果没有事件发生,请长时间hibernate( Thread.Sleep() )。
我没有考虑长时间睡眠的任何副作用,但一分钟的睡眠时间不应该消耗太多的资源。 如果它不是服务,我可能会进行终止检查,但我认为该服务并不意味着终止。