2012-04-18 17 views
6

Tengo un servicio de Windows en ejecución, dentro de esto quiero ejecutar una función cada minutos. He encontrado algún código pero parece que no funciona? Tengo un registrador y parece que no entra en la función timer_Elapsed alguna vez?cómo ejecutar una función dentro de un servicio cada 10 minutos?

protected override void OnStart(string[] args) 
    { 
     // SmartImportService.WebService.WebServiceSoapClient test = new WebService.WebServiceSoapClient(); 
     // test.Import(); 
     log.Info("Info - Service Started"); 
     _timer = new Timer(10 * 60 * 1000); // every 10 minutes?? 
     _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); 
    } 

    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) 
    { 
     log.Info("Info - Check time"); 
     DateTime startAt = DateTime.Today.AddHours(9).AddMinutes(48); 
     if (_lastRun < startAt && DateTime.Now >= startAt) 
     { 
      // stop the timer 
      _timer.Stop();    

      try 
      { 
       log.Info("Info - Import"); 
       SmartImportService.WebService.WebServiceSoapClient test = new WebService.WebServiceSoapClient(); 
       test.Import(); 
      } 
      catch (Exception ex) { 
       log.Error("This is my error - ", ex); 
      } 

      _lastRun = DateTime.Now; 
      _timer.Start(); 
     } 
    } 
+1

¿Necesita llamar al inicio del temporizador? –

+0

ver http://stackoverflow.com/questions/246697/windows-service-and-timer –

+0

ahhh yeeeeeeeee – Beginner

Respuesta

16

lo necesario para empezar el temporizador:

protected override void OnStart(string[] args) 
{ 
    log.Info("Info - Service Started"); 
    _timer = new Timer(10 * 60 * 1000); // every 10 minutes 
    _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); 
    _timer.Start(); // <- important 
} 
+4

Durante los 10 minutos, prefiero usar 'TimeSpan.FromMinutes (10) .TotalMilliseconds;' en lugar de '10 * 60 * 1000' – Jaider

3

no veo _timer.Start(), que debe ser su problema.

1

intente iniciar el timer,

protected override void OnStart(string[] args) 
    { 
     // SmartImportService.WebService.WebServiceSoapClient test = new WebService.WebServiceSoapClient(); 
     // test.Import(); 
     log.Info("Info - Service Started"); 
     _timer = new Timer(10 * 60 * 1000); // every 10 minutes?? 
      _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); 
_timer.Start(); 
    } 

    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) 
    { 
     log.Info("Info - Check time"); 
     DateTime startAt = DateTime.Today.AddHours(9).AddMinutes(48); 
     if (_lastRun < startAt && DateTime.Now >= startAt) 
     { 
      // stop the timer 
      _timer.Stop();    

      try 
      { 
       log.Info("Info - Import"); 
       SmartImportService.WebService.WebServiceSoapClient test = new WebService.WebServiceSoapClient(); 
       test.Import(); 
      } 
      catch (Exception ex) { 
       log.Error("This is my error - ", ex); 
      } 

      _lastRun = DateTime.Now; 
      _timer.Start(); 
     } 
    } 
2

Daniel Hilgarth es correcto - el principal problema es que nunca se llama Inicio en el temporizador.

Dicho esto, es posible que desee considerar también utilizar el Programador de tareas de Windows en lugar de un servicio con un temporizador. Esto le permite programar la tarea para que se ejecute cada 10 minutos, pero también cambiar la programación cuando lo desee sin un cambio en la compilación.

3

Necesito esta funcionalidad también. Es decir, mi servicio de Windows C# debe revisar el correo electrónico cada 10 minutos. Me desnudé cierta lógica para hacer el código más eficaz, de la siguiente manera:

private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) 
     { 
      _timer.Stop(); 
      try 
      { 
       EventLog.WriteEntry(Program.EventLogName, "Checking emails " + _count++); 
      } 
      catch (Exception ex) 
      { 
       EventLog.WriteEntry(Program.EventLogName, "This is my error " + ex.Message); 
      } 
      _timer.Start(); 
     } 

El método timer_elapsed de hecho será llamar cada 10 minutos, a partir de la primera _timer.start(), que se le pasa por la forma . No he hecho ninguna comprobación de _lastRun y ​​startAt. No creo que lo necesitemos

Cuestiones relacionadas