Pregunta

Necesito crear algún servicio de Windows que se ejecute cada N período de tiempo.
La pregunta es:
¿Qué control de temporizador debo usar: System.Timers.Timer o System.Threading.Timer uno? ¿Influye en algo?

Lo pregunto porque escuché muchas evidencias sobre el trabajo incorrecto de System.Timers.Timer en servicios de Windows.
Gracias.

¿Fue útil?

Solución

Ambos System.Timers.Timer y System.Threading.Timer funcionará para los servicios.

Los temporizadores que desea evitar son System.Web.UI.Timer y System.Windows.Forms.Timer , que son respectivamente para aplicaciones ASP y WinForms. El uso de estos hará que el servicio cargue un conjunto adicional que no es realmente necesario para el tipo de aplicación que está creando.

Utilice System.Timers.Timer como en el siguiente ejemplo (también, asegúrese de usar una variable de nivel de clase para evitar la recolección de basura, como se indica en la respuesta de 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
...
 */

Si elige System.Threading.Timer , puedes usarlo de la siguiente manera:

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();
        }
    }
}

Ambos ejemplos provienen de las páginas de MSDN.

Otros consejos

No uses un servicio para esto. Cree una aplicación normal y cree una tarea programada para ejecutarla.

Esta es la mejor práctica común. Jon Galloway está de acuerdo conmigo. O tal vez sea al revés. De cualquier manera, el hecho es que no es una práctica recomendada crear un servicio de Windows para realizar una tarea intermitente con un temporizador.

  

" Si está escribiendo un Servicio de Windows que ejecuta un temporizador, debe volver a evaluar su solución. "

     

–Jon Galloway, administrador de programas de la comunidad de ASP.NET MVC, autor, superhéroe de medio tiempo

Cualquiera de los dos debería funcionar bien. De hecho, System.Threading.Timer utiliza System.Timers.Timer internamente.

Habiendo dicho eso, es fácil hacer un mal uso de System.Timers.Timer. Si no almacena el objeto Timer en una variable en algún lugar, entonces es probable que se recolecte basura. Si eso sucede, tu cronómetro ya no disparará. Llame al método de Disposición para detener el temporizador, o use la clase System.Threading.Timer, que es un contenedor ligeramente más agradable.

¿Qué problemas has visto hasta ahora?

Estoy de acuerdo con el comentario anterior que podría ser mejor considerar un enfoque diferente. Mi sugerencia sería escribir una aplicación de consola y usar el programador de Windows:

Esto hará que:

  • Reduzca el código de plomería que replica el comportamiento del programador
  • Proporcionar mayor flexibilidad en términos del comportamiento de programación (por ejemplo, solo ejecutar los fines de semana) con toda la lógica de programación extraída del código de la aplicación
  • Utilice los argumentos de la línea de comando para parámetros sin tener que configurar los valores de configuracion en config archivos etc
  • Mucho más fácil de depurar / probar durante el desarrollo
  • Permitir que un usuario de soporte se ejecute invocando la aplicación de consola directamente (por ejemplo, útil durante el soporte situaciones)

Como ya se indicó, tanto System.Threading.Timer como System.Timers.Timer funcionarán. La gran diferencia entre los dos es que System.Threading.Timer es una envoltura alrededor de la otra.

  

System.Threading.Timer tendrá más manejo de excepciones mientras    System.Timers.Timer se tragará todas las excepciones.

Esto me dio grandes problemas en el pasado, así que siempre usaría 'System.Threading.Timer' y aún así manejaré muy bien tus excepciones.

Sé que este hilo es un poco viejo pero fue útil para un escenario específico que tuve y pensé que valía la pena notar que hay otra razón por la cual System.Threading.Timer podría ser Un buen enfoque. Cuando tiene que ejecutar periódicamente un trabajo que puede llevar mucho tiempo y desea asegurarse de que se utilice el período de espera completo entre los trabajos o si no desea que el trabajo se ejecute nuevamente antes de que el trabajo anterior haya finalizado, en el caso donde el trabajo toma más tiempo que el período del temporizador. Podría usar lo siguiente:

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();
            }
        }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top