Click here to Skip to main content
15,902,275 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
I have been trying to run a timer in my windows service. I tested the timer code below by simply starting an instance of notepad. So the timer appears to be firing, but when I go to insert or update to the db nothing happens. Any Suggestions?

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading;
using System.Globalization;
using System.Timers;
using System.Data.SqlClient;


namespace Monitor
{
    public partial class Service1 : ServiceBase
    {

        public int avg= 28;


        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            //timer1.Interval = 3000;
            timer1.Enabled = true;
            //timer1.Start();
        }

        protected override void OnStop()
        {
            timer1.Stop();
        }


        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
   
                              SqlConnection cs = new SqlConnection(@"Server=130-abcd-P-001.OSdd.LOCAL;Initial Catalog=AIM;User ID=user;Password=password");

                    SqlCommand cmd = new SqlCommand("select * from AIM where computerName='" + System.Environment.MachineName + "'", cs);

                    cmd.CommandType = CommandType.Text;

                    cmd.Connection = cs;

                    cs.Open();

                    SqlDataReader dr = cmd.ExecuteReader();


                    dr.Read();
                    if (dr.HasRows)
                    {
                        IPHostEntry host;
                        string localIP = "";
                        host = Dns.GetHostEntry(Dns.GetHostName());
                        foreach (IPAddress ip in host.AddressList)
                        {
                            if (ip.AddressFamily.ToString() == "InterNetwork")
                            {
                                localIP = ip.ToString();
                            }
                        }

                        SqlCommand update = new SqlCommand(@"Update AIM set latency = '" + avg + "', modifiedTime = '" + DateTime.Now + "' where computerName = '" + System.Environment.MachineName + "'", cs);
                        update.CommandType = CommandType.Text;
                        dr.Close();
                        update.ExecuteNonQuery();



                    }
                    else
                    {

                        IPHostEntry host;
                        string localIP = "";
                        host = Dns.GetHostEntry(Dns.GetHostName());
                        foreach (IPAddress ip in host.AddressList)
                        {
                            if (ip.AddressFamily.ToString() == "InterNetwork")
                            {
                                localIP = ip.ToString();
                            }
                        }
                        SqlCommand insert = new SqlCommand(@"Insert into AIM (computerName, latency, stationIP, modifiedTime) values ('" + System.Environment.MachineName + "', '" + avgRtt + "', '" + localIP + "', '" + DateTime.Now + "')", cs);
                        insert.CommandType = CommandType.Text;
                        dr.Close();
                        insert.ExecuteNonQuery();
                        cs.Close();



                    }
                    dr.Close();
                    cs.Close();

                }
            
        }


    }
Posted
Updated 30-May-13 17:52pm
v5
Comments
Sergey Alexandrovich Kryukov 30-May-13 18:08pm    
Well, first of all, not run Notepad. The Windows Service is not designed to start UI applications. Think about it: what if you log out, there is no desktop, but the service keeps executing.
And timers are bad. The most usual thing, especially in services, is a thread.
—SA
Dustin Prevatt 30-May-13 21:09pm    
SA, I know that a windows service is not designed to open applications. But If i open notepad from the onstart method it works fine (meaning it starts in and shows it in processes within the task manager.

Hello Dustin try with this code:

XML
private Timer timer1 = null;    //declaration


 protected override void OnStart(string[] args)
  {
    private Timer timer1 = null;
    timer1 = new Timer();
    this.timer1.Interval = Convert.ToDouble(1000); //timer intraval in milliseconds
    this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);
    timer1.Enabled = true;

  }

private void timer1_Tick(object sender, EventArgs e)
  {
               //write your code here
  }
 
Share this answer
 
v2
You should have new before OnElapsedEvent.
Check this link for a sample.
http://msdn.microsoft.com/en-us/library/system.timers.timer.elapsed.aspx[^]
 
Share this answer
 
Comments
Uttam Suthar 17-Jul-20 7:37am    
Thank you so much.. after googling for almost 2 days, i got this workaroud.
refer this solution it works:



Easy to learn Window Service[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900