0

i'm facing a strange problem with a Timer in a Windows service. is my first windows service, so for start to learn i decide to create a service that each 10 seconds write in a .txt file what time is it. i add the timer but looks like the timer never start. can you help me to understand where i'm wrong? here my code:

namespace testtimer
{
    public partial class TestTimer : ServiceBase
    {
        public TestTimer()
        {
            InitializeComponent();
            timer.Interval = 10000;
            timer.Enabled = true;
        }

        protected override void OnStart(string[] args)
        {
            timer.Start();
        }

        protected override void OnStop()
        {
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            string date = System.DateTime.Now.ToString();
            StreamWriter wr = new StreamWriter(@"C:\Users\xxx\Desktop\Test\testtimer.txt", true);

            wr.WriteLine("\n" + "The Time is:" + "\t" + date);
            wr.Close();
        }
    }
}

where i'm wrong?

thanks a lot for your help :)

Patrick Panci
  • 21
  • 1
  • 4

1 Answers1

1

Am guessing you are using a Windows.Forms timer (the component one, that you drag onto your design surface)....this needs a "window" and "message loop" in order to be able to process/receive the actual timer tick event.

When you're an NT service....you don't have a window...you're just a bit of code that has entry points that get called by the SCM (Service Control Manager).

You need to use a different type of timer that uses a thread, and will call back a function.

Community
  • 1
  • 1
Colin Smith
  • 12,375
  • 4
  • 39
  • 47
  • Thanks a lot! this is why i was testing the same functionality on a windows form and was working and in a service no...thanks for your time and for your help :)....Patrick – Patrick Panci Apr 26 '17 at 14:01