0

I'm trying to use a timer in a windows service, I install the service and start it up in the services but the timer won't fire. However when I use this exact same code in a console app then the timer fires. I have tried a lot of different suggestions and none of them seem to work for me in a windows service

Here is my code...

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.Threading.Tasks;
using System.Timers;
using System.IO;


namespace NextService
{
public partial class Service1 : ServiceBase
{
    private System.Timers.Timer aTimer;

    public Service1()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        aTimer = new System.Timers.Timer(10000);
        aTimer.Elapsed += new ElapsedEventHandler(aTimer_Elapsed);
        aTimer.Enabled = true;
        aTimer.AutoReset = true;
        aTimer.Start();

    }

    private static void aTimer_Elapsed(object sender, ElapsedEventArgs e)
    {
        string path = @"c:\MyTest.txt";
        if (!File.Exists(path))
        {
            // Create a file to write to. 
            using (StreamWriter sw = File.CreateText(path))
            {
                sw.WriteLine("Hello");
                sw.WriteLine("And");
                sw.WriteLine("Welcome" + DateTime.Now.ToString());
            }
        }
        //throw new NotImplementedException();
    }

    protected override void OnStop()
    {

    }

}

}

I just don't understand why it will work in a console app and not in this service. I'm just having it create a file on the fire event to test before I put my code to it.

Thanks

Updated Code with Thread timer

 protected override void OnStart(string[] args)
    {
        TimerCallback callback = aTimer_Elapsed;
        Timer timer = new Timer(callback);
        timer.Change(TimeSpan.Zero, TimeSpan.FromSeconds(10));
        Thread.Sleep(10000);

    }

    private void aTimer_Elapsed(object state)
    {
        string path = @"c:\MyTest.txt";
        if (!File.Exists(path))
        {
            // Create a file to write to. 
            using (StreamWriter sw = File.CreateText(path))
            {
                sw.WriteLine("Hello");
                sw.WriteLine("And");
                sw.WriteLine("Welcome" + DateTime.Now.ToString());
            }
        }
    }
Chris
  • 2,953
  • 10
  • 48
  • 118
  • 1
    This could be a problem with file permissions. Is the user account the service is running under an owner of `C:\`? Check the event log for errors from the service. I bet the timer is firing, but the service is failing at creating the file. – Dan Nov 25 '13 at 18:16
  • I have it set to localservice, I have my UAC disabled – Chris Nov 25 '13 at 18:19
  • Never skip using try/catch in a timer's Elapsed event handler. It will swallow exceptions without a diagnostic. You'll need to log the exception in your catch clause. – Hans Passant Nov 25 '13 at 18:36
  • @HansPassant, I know I am guilty of not using a try catch finally. I should get into the habit of using it. – Chris Nov 25 '13 at 18:56

1 Answers1

0

I will not explain everything other already explained before so follow the links:

Duplicated question?
Possible Complete Answer

Community
  • 1
  • 1
EProgrammerNotFound
  • 2,403
  • 4
  • 28
  • 59
  • Thanks for the links, the one entitled "Duplicated question?" was the one that explained so I understood. – Chris Nov 25 '13 at 18:33
  • 1
    Only a System.Windows.Forms.Timer needs a message loop. System.Timers.Timer as used by the OP has no such requirement. – Hans Passant Nov 25 '13 at 18:38
  • @HansPassant Thanks, IMO, this question should be marked as duplicated – EProgrammerNotFound Nov 25 '13 at 18:43
  • I changed it over to a threading timer, but now when I go to start the service I get an error saying could not be started on local machine – Chris Nov 25 '13 at 18:44
  • @MatheusFreitas, yes this could be a duplicate question, but I did try everything other than a thread timer, that's why I had to ask incase I was missing something that I may have glossed over, and I was missing something, I was doing it wrong. – Chris Nov 25 '13 at 18:45
  • @MatheusFreitas, I edited an added the new code for using the threading timer...after I install the service and try starting it is when I get the error about it not being able to start on localmachine – Chris Nov 25 '13 at 18:52