Why does the timer not work in a Windows service?

I know this is already a asked question, but I have not found 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 to my Mylog.txt file every 5 seconds, but nothing happens even after 2 minutes. If I put the WriteTimeToFile() function in the OnStart method, it works fine, but not in the timer.

Any help would be greatly appreciated.

+4
source share
4 answers

Well, after a few hours, I noticed that the timer was working fine. There was nothing wrong with the timer. But the problem is in the FileStream constructor. FileMode.Append only works FileAccess.Write .

Thus, fixing this line of code solved the problem.

Anyway, thanks for watching.

 using (FileStream fs = new FileStream(@"d:\mylog.txt", FileMode.Append, FileAccess.Write)) 
+1
source

What is a timer namespace? It should be System.Timers.Timer or System.Threading.Timer .

See here: Best Timer to Use in a Windows Service

+5
source

The service must run under a Windows account with write permissions to the D: \ directory.

Check the exceptions in the event viewer to see if an unauthorized access exception exists.

Also place a breakpoint in the _timer_Elapsed method to make sure it is called and passes through the code.

0
source

Windows service with timer

Read my answer in this post ...

Perhaps you skip timer.AutoReset = true;

0
source

Source: https://habr.com/ru/post/1440926/


All Articles