Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the timer not working in windows service?

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.

like image 292
Mojtaba pirveisi Avatar asked Oct 20 '12 07:10

Mojtaba pirveisi


People also ask

Does system timers timer run in a separate thread?

Yes, they run in a different thread.

Is system threading timer thread safe?

Timer is not thread-safe.

How do I stop a timer elapsed event?

It would have already queued before you have called Stop method. It will fire at the elapsed time. To avoid this happening set Timer. AutoReset to false and start the timer back in the elapsed handler if you need one.


1 Answers

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

like image 125
urlreader Avatar answered Oct 14 '22 09:10

urlreader