6

I know this is an already asked question, but I couldn't find any solution. Here is my service.

class Program : ServiceBase
{
    private  Timer _timer;
    public Program()
    {
        ServiceName = "PrintTime";
    }

    static void Main(string[] args)
    {
        Run(new Program());
    }

    protected override void OnStart(string[] args)
    {
        base.OnStart(args);
        _timer = new Timer(5000);
        _timer.Elapsed += _timer_Elapsed;
        _timer.Start();
    }

    void _timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        WriteTimeToFile();
    }

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

    private void WriteTimeToFile()
    {
        using (FileStream fs = new FileStream(@"d:\mylog.txt", FileMode.Append,            FileAccess.ReadWrite))
        {
            StreamWriter streamWriter = new StreamWriter(fs);
            streamWriter.Write(DateTime.Now.ToShortTimeString());
            streamWriter.Close();
            fs.Close();
        }
    }

}

As you can see I want to write currentTime into my Mylog.txt file every 5 seconds, but nothing happens after even 2 minutes. If I put the WriteTimeToFile() function into OnStart method it works fine, but not in a timer.

Any help would be greatly appreciated.

jarlh
  • 42,561
  • 8
  • 45
  • 63
Mojtaba pirveisi
  • 81
  • 1
  • 2
  • 6

4 Answers4

6

What is the timer's namespace? It needs to be System.Timers.Timer or System.Threading.Timer.

See here: Best Timer for using in a Windows service

Community
  • 1
  • 1
urlreader
  • 6,319
  • 7
  • 57
  • 91
1

Ok, after several hours, I noticed that the timer works fine. There was nothing wrong with timer. But the problem is about FileStream constructor. FileMode.Append only works by FileAccess.Write.

So fixing this line of code solved the problem .

Anyway, thanks for your attention.

using (FileStream fs = new FileStream(@"d:\mylog.txt", 
                       FileMode.Append, FileAccess.Write))
nabulke
  • 11,025
  • 13
  • 65
  • 114
Mojtaba pirveisi
  • 81
  • 1
  • 2
  • 6
0

The Service must be running under a Windows account with permissions to write to the D:\ directory.

Check the exceptions in Event Viewer to see if there is an unauthorized access exception.

Also put a break point in the _timer_Elapsed method to verify that it gets called and step through the code.

Zaid Masud
  • 13,225
  • 9
  • 67
  • 88
0

Windows service with timer

Read my answer in this post...

Maybe you miss timer.AutoReset = true;

Community
  • 1
  • 1
T-moty
  • 2,679
  • 1
  • 26
  • 31