So I managed to write the service and its working fine for now. I am suppose to make sure that when the database record are processed, and for some reason if the service is paused or shutting down, the task should be completed instead of leaving the data inconsistent.
I have tried the below code, but I feel it might not be correct, in case it is, it might not be the best. How can I improve this code for the above scenario?
protected override void OnStart(string[] args)
{
// Update the service state to Start Pending.
ServiceStatus serviceStatus = new ServiceStatus();
serviceStatus.dwCurrentState = ServiceState.SERVICE_START_PENDING;
serviceStatus.dwWaitHint = 100000;
SetServiceStatus(this.ServiceHandle, ref serviceStatus);
_eventLog.WriteEntry("RMS Service Started: " + DateTime.UtcNow.ToLongDateString());
CheckDBEntryData();
_timer = new System.Timers.Timer();
_timer.Interval = 60000;
_timer.Elapsed += new System.Timers.ElapsedEventHandler(this.SendScheduledSMS);
_timer.Start();
// Update the service state to Running.
serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING;
SetServiceStatus(this.ServiceHandle, ref serviceStatus);
}
public void SendScheduledSMS(object sender, System.Timers.ElapsedEventArgs e)
{
if (!_isTaskRunning)
{
_timer.Enabled = false;
_isTaskRunning = true;
_eventLog.WriteEntry("RMS Timer Event started: " + DateTime.UtcNow.ToLongDateString());
//TODO: Write the code to check pending RMS and process them
_eventLog.WriteEntry("RMS Timer Event stopped: " + DateTime.UtcNow.ToLongDateString());
_isTaskRunning = false;
_timer.Enabled = true;
}
}
protected override void OnStop()
{
CanStop = !_isTaskRunning;
// Update the service state to Stop Pending.
ServiceStatus serviceStatus = new ServiceStatus();
serviceStatus.dwCurrentState = ServiceState.SERVICE_STOP_PENDING;
serviceStatus.dwWaitHint = 100000;
SetServiceStatus(this.ServiceHandle, ref serviceStatus);
_eventLog.WriteEntry("RMS Service Stopped: " + DateTime.UtcNow.ToLongDateString());
// Update the service state to Stopped.
serviceStatus.dwCurrentState = ServiceState.SERVICE_STOPPED;
SetServiceStatus(this.ServiceHandle, ref serviceStatus);
}
More Info
Service is processing the database record and passing the data to 2nd remote server, which is responsible for sending SMS notification to users. I need to make sure that notification is sent only once. If I use transaction, and a rollback happens for the last record, next time the processing starts, it will send notifications from beginning, thus sending repeat notifications. Therefore I cannot rely on DB transaction modal, as I have no control over the 2nd remote server.