visual una studio servicio llamar instalar instalador hora ejecutar determinada desde crear c# timer windows-services

c# - una - El mejor temporizador para usar en un servicio de Windows



servicio windows c# timer (6)

Necesito crear un servicio de Windows que se ejecutará cada N período de tiempo.
La pregunta es:
¿Qué control de temporizador debería usar: System.Timers.Timer o System.Threading.Timer uno? ¿Influye en algo?

Lo estoy preguntando porque escuché muchas evidencias del trabajo no correcto de System.Timers.Timer en los servicios de Windows.
Gracias.


Como ya se dijo, tanto System.Threading.Timer como System.Timers.Timer funcionarán. La gran diferencia entre los dos es que System.Threading.Timer es un contenedor alrededor del otro.

System.Threading.Timer tendrá más System.Threading.Timer 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 manejaría muy bien sus excepciones.


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

Una vez dicho esto, 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 sea basura recolectada. Si eso sucede, su temporizador ya no se disparará. Llame al método Dispose 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:

Esta voluntad:

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

No use un servicio para esto. Crea una aplicación normal y crea una tarea programada para ejecutarla.

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

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

-Jon Galloway, ASP.NET MVC community program manager, autor, superhéroe a tiempo parcial


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 todo el período de espera se utiliza entre trabajos o si no desea que el trabajo se ejecute nuevamente antes de que el trabajo anterior haya terminado en el caso donde el trabajo lleva más tiempo que el período del temporizador. Puede 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(); } }


Tanto System.Timers.Timer como System.Threading.Timer funcionarán para los servicios.

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

Use 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 , puede usar 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.