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());
}
}
}