none
Windows Service using Timer starting then immediately stopping

    Question

  • I am creating a C# Windows service that extracts data once a day at a configured time. 

    In the service code, for the OnStart, I am setting up a timer, adding an event handler to the timer, turning off AutoReset, and calculating the timer interval based on the amount of time to the next run.  I am then enabling the timer, and Start() ing the timer.  The event handler first checks for the AutoReset being off, and if it is, it resets the timer interval to 24 hours, and turns AutoReset on, then runs the data extract job.  This way, after the first run, the service sets up to run every day at the same time. 

    The problem I am having is that as soon as I start the service, it stops, saying that it Started then stopped, perhaps it had no work to do, etc. 

    Here is the Service code:

    using System;
    using System.ServiceProcess;
    using System.Timers;
    using PaymentAnalysisLibrary;
    
    namespace PaymentAnalysisReportService
    {
      public partial class PaymentAnalysisReportService : ServiceBase
      {
        private Timer ReportTimer;
        public PaymentAnalysisReportService()
        {
          InitializeComponent();
        }
        protected override void OnStart(string[] args)
        {
          ReportTimer = new Timer();
          ReportTimer.AutoReset = false;
          ReportTimer.Elapsed += new ElapsedEventHandler(this.ReportTimer_Elapsed);
    
          // Set interval for the next occurence of the scheduled time
          DateTime NextRun = DateTime.Today + Properties.Settings.Default.ScheduledTime;
          if (NextRun < DateTime.Now)
            NextRun += TimeSpan.FromDays(1);
          ReportTimer.Interval = (NextRun - DateTime.Now).TotalMilliseconds;
          ReportTimer.Enabled = true;
          ReportTimer.Start();
        }
        protected override void OnStop()
        {
          ReportTimer.Elapsed -= new ElapsedEventHandler(this.ReportTimer_Elapsed);
          ReportTimer.Dispose();
        }
        private void ReportTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
          if (!ReportTimer.AutoReset)
          {
            // Once the first runtime has been reached, set the timer to elapse every 24 hoursReportTimer.Interval = TimeSpan.FromDays(1).TotalMilliseconds;
            ReportTimer.Interval = Properties.Settings.Default.OneDayInMilliseconds;
            ReportTimer.AutoReset = true;
          }
          GlobalItems.CreateReport(DateTime.Today - TimeSpan.FromDays(1));
        }
      }
    }
    
    I have modified the properties of the service so that CanStop is set to False.  I am not sure what else to do, so that the service stops stopping.  Any ideas?
    Friday, September 03, 2010 1:45 AM

Answers

  • You probably encountered an exception.  By default, .NET does not do a good job of logging these for services.

    Do both of the following:

    1.  To catch errors in OnStart:  Wrap everything in OnStart with a try/catch of Exception.  Log the error, then rethrow it.

    2.  To catch errors elsewhere:  First thing in OnStart, add a handler for the AppDomain.CurrentDomain.UnhandledException event.  In the handler log the error.

    Note that if you are just starting on this service, it might be easier to build this as a console application so that it is simple to debug.  Main is your OnStart.  Port it into a service (which will be trivial) once you are nearly done.

     

    Friday, September 03, 2010 3:13 AM

All replies

  • You probably encountered an exception.  By default, .NET does not do a good job of logging these for services.

    Do both of the following:

    1.  To catch errors in OnStart:  Wrap everything in OnStart with a try/catch of Exception.  Log the error, then rethrow it.

    2.  To catch errors elsewhere:  First thing in OnStart, add a handler for the AppDomain.CurrentDomain.UnhandledException event.  In the handler log the error.

    Note that if you are just starting on this service, it might be easier to build this as a console application so that it is simple to debug.  Main is your OnStart.  Port it into a service (which will be trivial) once you are nearly done.

     

    Friday, September 03, 2010 3:13 AM
  • Thanks! It was a reference problem that happened when I switched from the 4.0 framework to the 3.5.  I assumed any errors would trickle up and be shown somewhere. 
    Friday, September 03, 2010 3:57 PM