在Windows服务中使用的最佳计时器

时间:2008-10-29 13:00:42

标签: c# timer windows-services

我需要创建一些Windows服务,每隔N段执行一次 问题是:
我应该使用哪个计时器控件:System.Timers.TimerSystem.Threading.Timer一个?它对某些事物有影响吗?

我在问,因为我在Windows服务中听到很多证据证明System.Timers.Timer的工作不正确 谢谢。

6 个答案:

答案 0 :(得分:118)

System.Timers.TimerSystem.Threading.Timer都适用于服务。

您要避免的计时器是System.Web.UI.TimerSystem.Windows.Forms.Timer,它们分别用于ASP应用程序和WinForms。使用这些将导致服务加载一个额外的程序集,这对于您正在构建的应用程序类型并不是真正需要的。

使用System.Timers.Timer,如下例所示(同样,请确保使用类级别变量来防止垃圾回收,如Tim Robinson的回答所述):

using System;
using System.Timers;

public class Timer1
{
    private static System.Timers.Timer aTimer;

    public static void Main()
    {
        // Normally, the timer is declared at the class level,
        // so that it stays in scope as long as it is needed.
        // If the timer is declared in a long-running method,  
        // KeepAlive must be used to prevent the JIT compiler 
        // from allowing aggressive garbage collection to occur 
        // before the method ends. (See end of method.)
        //System.Timers.Timer aTimer;

        // Create a timer with a ten second interval.
        aTimer = new System.Timers.Timer(10000);

        // Hook up the Elapsed event for the timer.
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

        // Set the Interval to 2 seconds (2000 milliseconds).
        aTimer.Interval = 2000;
        aTimer.Enabled = true;

        Console.WriteLine("Press the Enter key to exit the program.");
        Console.ReadLine();

        // If the timer is declared in a long-running method, use
        // KeepAlive to prevent garbage collection from occurring
        // before the method ends.
        //GC.KeepAlive(aTimer);
    }

    // Specify what you want to happen when the Elapsed event is 
    // raised.
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
    }
}

/* This code example produces output similar to the following:

Press the Enter key to exit the program.
The Elapsed event was raised at 5/20/2007 8:42:27 PM
The Elapsed event was raised at 5/20/2007 8:42:29 PM
The Elapsed event was raised at 5/20/2007 8:42:31 PM
...
 */

如果您选择System.Threading.Timer,则可以按如下方式使用:

using System;
using System.Threading;

class TimerExample
{
    static void Main()
    {
        AutoResetEvent autoEvent     = new AutoResetEvent(false);
        StatusChecker  statusChecker = new StatusChecker(10);

        // Create the delegate that invokes methods for the timer.
        TimerCallback timerDelegate = 
            new TimerCallback(statusChecker.CheckStatus);

        // Create a timer that signals the delegate to invoke 
        // CheckStatus after one second, and every 1/4 second 
        // thereafter.
        Console.WriteLine("{0} Creating timer.\n", 
            DateTime.Now.ToString("h:mm:ss.fff"));
        Timer stateTimer = 
                new Timer(timerDelegate, autoEvent, 1000, 250);

        // When autoEvent signals, change the period to every 
        // 1/2 second.
        autoEvent.WaitOne(5000, false);
        stateTimer.Change(0, 500);
        Console.WriteLine("\nChanging period.\n");

        // When autoEvent signals the second time, dispose of 
        // the timer.
        autoEvent.WaitOne(5000, false);
        stateTimer.Dispose();
        Console.WriteLine("\nDestroying timer.");
    }
}

class StatusChecker
{
    int invokeCount, maxCount;

    public StatusChecker(int count)
    {
        invokeCount  = 0;
        maxCount = count;
    }

    // This method is called by the timer delegate.
    public void CheckStatus(Object stateInfo)
    {
        AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
        Console.WriteLine("{0} Checking status {1,2}.", 
            DateTime.Now.ToString("h:mm:ss.fff"), 
            (++invokeCount).ToString());

        if(invokeCount == maxCount)
        {
            // Reset the counter and signal Main.
            invokeCount  = 0;
            autoEvent.Set();
        }
    }
}

这两个示例都来自MSDN页面。

答案 1 :(得分:37)

请勿使用服务。创建一个普通的应用程序并创建一个计划任务来运行它。

这是最常见的最佳做法。 Jon Galloway agrees with me. Or maybe its the other way around.无论哪种方式,事实是创建一个Windows服务以执行一个计时器的间歇性任务并不是最好的做法。

  

“如果您正在编写运行计时器的Windows服务,则应重新评估您的解决方案。”

     

-Jon Galloway,ASP.NET MVC社区项目经理,作者,兼职超级英雄

答案 2 :(得分:7)

任何一个都应该正常工作。实际上,System.Threading.Timer在内部使用System.Timers.Timer。

话虽如此,很容易误用System.Timers.Timer。如果你没有将Timer对象存储在某个变量中,那么它很容易被垃圾收集。如果发生这种情况,您的计时器将不再发射。调用Dispose方法来停止计时器,或使用System.Threading.Timer类,这是一个稍好的包装器。

到目前为止,您看到了什么问题?

答案 3 :(得分:2)

我同意之前的评论,可能最好考虑采用不同的方法。我的建议是编写一个控制台应用程序并使用Windows调度程序:

这将:

  • 减少复制调度程序行为的管道代码
  • 提供更大的灵活性 调度行为(例如,仅限于 从周末开始运行所有从应用程序代码中抽象出来的调度逻辑
  • 使用命令行参数 对于参数而不必 在config中设置配置值 文件等
  • 在开发过程中更容易调试/测试
  • 允许支持用户通过调用执行 控制台应用程序直接 (例如在支持期间有用) 情况下)

答案 4 :(得分:1)

如上所述,System.Threading.TimerSystem.Timers.Timer都可以使用。两者之间的最大区别在于System.Threading.Timer是另一个的包装器。

  

System.Threading.Timer会有更多异常处理   System.Timers.Timer将吞下所有例外。

这给了我过去的大问题所以我总是会使用'System.Threading.Timer'并且仍能很好地处理你的异常。

答案 5 :(得分:0)

我知道这个帖子有点旧,但它对于我所拥有的特定场景很方便,我认为值得注意的是,System.Threading.Timer可能是一个好方法的另一个原因。 当您必须定期执行可能需要很长时间的作业并且您希望确保在作业之间使用整个等待期间,或者如果您不想在上一个作业完成之前再次运行该作业时作业所需时间超过计时器时间的情况。 您可以使用以下内容:

using System;
using System.ServiceProcess;
using System.Threading;

    public partial class TimerExampleService : ServiceBase
    {
        private AutoResetEvent AutoEventInstance { get; set; }
        private StatusChecker StatusCheckerInstance { get; set; }
        private Timer StateTimer { get; set; }
        public int TimerInterval { get; set; }

        public CaseIndexingService()
        {
            InitializeComponent();
            TimerInterval = 300000;
        }

        protected override void OnStart(string[] args)
        {
            AutoEventInstance = new AutoResetEvent(false);
            StatusCheckerInstance = new StatusChecker();

            // Create the delegate that invokes methods for the timer.
            TimerCallback timerDelegate =
                new TimerCallback(StatusCheckerInstance.CheckStatus);

            // Create a timer that signals the delegate to invoke 
            // 1.CheckStatus immediately, 
            // 2.Wait until the job is finished,
            // 3.then wait 5 minutes before executing again. 
            // 4.Repeat from point 2.
            Console.WriteLine("{0} Creating timer.\n",
                DateTime.Now.ToString("h:mm:ss.fff"));
            //Start Immediately but don't run again.
            StateTimer = new Timer(timerDelegate, AutoEventInstance, 0, Timeout.Infinite);
            while (StateTimer != null)
            {
                //Wait until the job is done
                AutoEventInstance.WaitOne();
                //Wait for 5 minutes before starting the job again.
                StateTimer.Change(TimerInterval, Timeout.Infinite);
            }
            //If the Job somehow takes longer than 5 minutes to complete then it wont matter because we will always wait another 5 minutes before running again.
        }

        protected override void OnStop()
        {
            StateTimer.Dispose();
        }
    }

    class StatusChecker
        {

            public StatusChecker()
            {
            }

            // This method is called by the timer delegate.
            public void CheckStatus(Object stateInfo)
            {
                AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
                Console.WriteLine("{0} Start Checking status.",
                    DateTime.Now.ToString("h:mm:ss.fff"));
                //This job takes time to run. For example purposes, I put a delay in here.
                int milliseconds = 5000;
                Thread.Sleep(milliseconds);
                //Job is now done running and the timer can now be reset to wait for the next interval
                Console.WriteLine("{0} Done Checking status.",
                    DateTime.Now.ToString("h:mm:ss.fff"));
                autoEvent.Set();
            }
        }