Note that there are some explanatory texts on larger screens.

plurals
  1. POTimer not firing in Windows Service but fires when in a console app
    primarykey
    data
    text
    <p>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</p> <p>Here is my code...</p> <pre><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() { } } </code></pre> <p>}</p> <p>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.</p> <p>Thanks</p> <p>Updated Code with Thread timer</p> <pre><code> 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()); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload