Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite while loop in Windows Service

I have a windows in which i have added an infinite while loop in the OnStart() method .I have tested the service for 1 hour and it is running fine.But as this is my first Windows Service so have doubt on the performance with infinite loop. Here is the code..

 protected override void OnStart(string[] args)
    {
       while(true){

        string Query="";

        Query = "SELECT * FROM 'reportsetting` order by SendingTime;";

        MySqlConnection con = new MySqlConnection(conn);
        MySqlCommand comm = new MySqlCommand(Query, con);
        con.Open();
        MySqlDataReader dr = comm.ExecuteReader();
        while (dr.Read())
        {

            time = dr["SendingTime"].ToString();

            if ((str = DateTime.Now.ToString("HH:mm")).Equals(time))
            {

                //Execute Function and send reports based on the data from the database.

                Thread thread = new Thread(sendReports);
                thread.Start();

            }


        }


            //Halt for this Moment

            while ((str = DateTime.Now.ToString("HH:mm")).Equals(time))
            {


            }


         }

        }

    public void sendReports() { 



    }

So want to know if it will be Ok for long run.Thanks..

like image 456
user3924730 Avatar asked Jan 10 '23 22:01

user3924730


1 Answers

To re-run the query every 40 seconds:

private const string Query = "SELECT * FROM 'reportsetting` order by SendingTime;"

protected override void OnStart(string[] args)
{
    _timer = new Timer(40 * 1000); // every 40 seconds
    _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
    _timer.Start(); // <- important
}

private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    MySqlConnection con = new MySqlConnection(conn);
    MySqlCommand comm = new MySqlCommand(Query, con);
    con.Open();
    MySqlDataReader dr = comm.ExecuteReader();
    while (dr.Read())
    {

        time = dr["SendingTime"].ToString();

        if ((str = DateTime.Now.ToString("HH:mm")).Equals(time))
        {

            //Execute Function and send reports based on the data from the database.

            Thread thread = new Thread(sendReports);
            thread.Start();
        }
    }
}

Something like that. As Groo mentioned though, you might want to dispose of the connection every time so you don't have that hanging around in memory.

like image 156
James Cross Avatar answered Jan 22 '23 16:01

James Cross