Link to home
Start Free TrialLog in
Avatar of Paramhans
Paramhans

asked on

Timer not working properly in windows service

Hi Experts,

          I have written windows service interact with database. I have used two timers in that. first timer is used to read settings for the service for a xml file(sample is given) also checks if the system time is between starttime and end time of xml file then it enables the second timer else disable the second timer. The second timer is fired at time interval specified in xml file. method ProcessInvoiceBatch() is called by second timer.

code sample is attached.

My problem is that every thing works fine, but after some times the second timer stops working without any reason. means elapsed event of second timer stops firing. first timer is working properly because when i change the time interval for second timer in xml file second timer starts firing again. and again after some time ti stops.


I dont know what is causing this problem.

i m using Windows Server 2003 Sp2 machine.

Can anyone please help me overcoming this problem.

Regards,
Paramhans
// Windows service Code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Configuration;
using System.Timers;
using System.Data.SqlClient;
using System.Collections;
using System.IO;
using System.Xml;
 
namespace WinService_For_Processing_Invoice_Batch
{
    public partial class InvoiceBatchProcessingService : ServiceBase
    {
        Timer Tim = new Timer();
        Timer TimerUpdateSettings = new Timer();
        SqlConnection con;
        string StartTime, StopTime, ServiceName, TimeInterval, ServerName, DatabaseName, UserId, Password, LogFilePath;
 
        ConnectionClass cnCls;
        SqlCommand CmdInvoiceBatch, cmdBillingAwb, cmdSumAmt, CmdInvoiceHeader;
        string invoice_batch, branch_code, service, start_date, end_date, invoice_date, commercial_id;
        string StrQuery;
        SqlDataReader FetchInvoices, GetBillingData;
        SqlParameter param;
        localhost.LineHaul_Billing_Service ProcessInvoice = new localhost.LineHaul_Billing_Service();
 
        public InvoiceBatchProcessingService()
        {
            InitializeComponent();
 
            GetSettings();
 
            cnCls = new ConnectionClass(ServerName, DatabaseName, UserId, Password);
        }
 
        protected override void OnStart(string[] args)
        {
            Tim.Elapsed += new ElapsedEventHandler(Tim_Elapsed);
            TimerUpdateSettings.Elapsed += new ElapsedEventHandler(TimerUpdateSettings_Elapsed);
            addTOLog("Service Started................");
            
            TimerUpdateSettings.Interval = 60000;
            TimerUpdateSettings.Enabled = true;
 
            Tim.Enabled = true;
        }
 
        protected override void OnStop()
        {
            addTOLog("Service Stoped...............");
            Tim.Enabled = false;
            TimerUpdateSettings.Enabled = false;
        }
 
        void TimerUpdateSettings_Elapsed(object sender, ElapsedEventArgs e)
        {
            GetSettings();
            if ((DateTime.Now >= Convert.ToDateTime(StartTime)) && (DateTime.Now <= Convert.ToDateTime(StopTime)))
            {
                Tim.Enabled = true;
            }
            else
            {
                Tim.Enabled = false;
            }
        }
 
        protected void Tim_Elapsed(object source, ElapsedEventArgs e)
        {
            ProcessInvoiceBatch();
        }
 
        private void ProcessInvoiceBatch()
        {
           //my code;
        }
 
        public void addTOLog(string Message)
        {
            FileStream f = new FileStream(LogFilePath + "Logs_For_" + DateTime.Now.ToShortDateString().Replace('/', '_') + ".log", FileMode.Append);
            StreamWriter sw = new StreamWriter(f);
            sw.WriteLine("Log entry at " + DateTime.Now + ": " + Message);
            sw.Close();
            f.Close();
        }
 
        private void GetSettings()
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(@"path of my local drive\WinServiceSettings.xml");
            XmlNode node;
            node = xmlDoc.SelectSingleNode("//Setting[@ServiceName='InvoiceBatchProcessingService']");
 
            foreach (XmlAttribute a in node.Attributes)
            {
                switch (a.Name)
                {
                    case "StartTime":
                        StartTime = a.Value;
                        break;
                    case "StopTime":
                        StopTime = a.Value;
                        break;
                    case "ServiceName":
                        ServiceName = a.Value;
                        break;
                    case "TimeInterval":
                        TimeInterval = a.Value;
                        break;
                    case "ServerName":
                        ServerName = a.Value;
                        break;
                    case "DatabaseName":
                        DatabaseName = a.Value;
                        break;
                    case "UserId":
                        UserId = a.Value;
                        break;
                    case "Password":
                        Password = a.Value;
                        break;
                    case "LogFilePath":
                        LogFilePath = a.Value;
                        break;
                }
            }
 
            Tim.Interval = Convert.ToDouble(TimeInterval);
        }
    }
}
 
 
 
// Settings XML file.
 
<?xml version="1.0" encoding="utf-8" ?>
<Settings>
	<Setting 
		ServiceName="ServiceName" 
		StartTime="11:00" 
		StopTime="22:55"
		TimeInterval="60000"
		ServerName="MyServer"
		DatabaseName="MyDB"
		UserId=""
		Password=""
		LogFilePath="D:\Application_Data\Billing_Logs\WindowsService\Bill_Processing_Logs\" />
	
</Settings>

Open in new window

SOLUTION
Avatar of Marcus Keustermans
Marcus Keustermans
Flag of South Africa 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 Paramhans
Paramhans

ASKER

Hi keustermans,

      First of all thanx for your reply.

       Now as per your suggestions goes:

       1) I need two timers first to get the settings at every min. or may be every sec. so that as soon as the xml file is updated it should get reflated in the service too. also my requirement was to fire the method "ProcessInvoiceBatch" every hour or at interval decided by the client. if i use only one timer both my requirements cant be fulfilled (as far as i can think). suppose client fixes time interval to 1 hour and starts the service and after some time he realizes he needs to set it to 30 mins. then the setting will change only after one hour. but in my case it will be affected only after 1 min and the method will be executed after 30 mins.

        2) Your second suggestion is good one and I'm surly gonna try this.

        3) As far as third on goes My client need a solution where he can store settings for more then one similar kind of win services at one location so that he dont hv to go to diffrent app.config files for changing the settings.



Thanx again for your reply.

Regards,
Paramhans
ASKER CERTIFIED SOLUTION
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
Thanx keustermans. I'll defiantly try it.