Link to home
Start Free TrialLog in
Avatar of YZlat
YZlatFlag for United States of America

asked on

Scheduling Windows Service

I have a Windows Service that I need to run every hour but I want it done programmatically, not via Windows Scheduler. Perhaps using a Timer or something.

Can someone tell me the best way I can accomplish that? I will need some code examples too
ASKER CERTIFIED SOLUTION
Avatar of wdosanjos
wdosanjos
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of YZlat

ASKER

Exactly what I needed! Thank you
I'm glad I could help.  

BTW, a quick note about the code.  Because on line #32 & #38 the timer is Disabled/Enabled the next process run is 1 hour after the last execution completed.  To run the process once every hour the code needs to be a little different as shown below:

namespace MyApp
{
    public partial class MyAppService : ServiceBase
    {
        private const double INTERVAL =  60 * 60 * 1000; // 60 mins (60 * 60 * 1000 millisecs); Ideally this should come from a configuration file

        private System.Timers.Timer _timer = new System.Timers.Timer();

        public MyAppService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            // Service Started
            
            _timer.Elapsed += new ElapsedEventHandler(Timer_Elapsed);
            
            _timer.Interval = 1000;  // Executes the first run after 1 sec

            _timer.Enabled = true;
        }

        protected override void OnStop()
        {
            _timer.Enabled = false;

            // Service Stopped
        }

        protected void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (_timer.Interval != INTERVAL)
                _timer.Interval = INTERVAL; // Reset the timer interval to the regular value

            ServiceTask();
        }

        private void ServiceTask()
        {
            try
            {
                // <<<<< Add your service processing code here >>>>>
            }
            catch (Exception ex)
            {
                // Log exception
            }
        }
    }
}

Open in new window