YZlat
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
Can someone tell me the best way I can accomplish that? I will need some code examples too
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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:
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
}
}
}
}
ASKER
Thank you for the clarification.
Could you also help me with this question:
https://www.experts-exchange.com/questions/27664066/How-can-I-use-a-timer-to-schedule-exe-to-run-at-a-specific-time.html
Could you also help me with this question:
https://www.experts-exchange.com/questions/27664066/How-can-I-use-a-timer-to-schedule-exe-to-run-at-a-specific-time.html
ASKER