I have a windows service which, among other things, needs to do some database maintenance every 24 hours. (SQL express, so can't schedule it inside the database)
For this I have created a Timer with a callback to the database maintenance method, but it appears to only get hit once (upon creation of the timer, I assume). I assumed this was due to the timer itself getting out of scope and being GC'd, but none of the sollutions I've tried seem to be working
The basic layout of the service is like this:
WindowsService.cs:
protected override void OnStart(string[] args)
{
ThreadPool.QueueUserWorkItem(StartServices);
}
private void StartServices() { Manager.Start(); }
Manager.cs:
public class Manager
{
private static Timer MaintenanceTimer;
public static void Start()
{
MaintenanceTimer = new Timer(DoMaintenance);
MaintenanceTimer.Change(new TimeSpan(0), new TimeSpan(24,0,0,0)); //I use 1 minute for testing
}
}
Obviously this code is severely simplified, but this is pretty much what happens. As stated before, I believe GC is the problem, which made me try the following 2 things:
- Use the constructor Timer(callback), so it will provide a self-reference to the callback. However, this would still not prevent it from running out of scope, so that's a no go.
- Define the timer as a static variable inside the Manager class. This should prevent it from ever being GC'd, but still doesn't appear to have it be called every 24 hours.
Any help in this matter would be greatly appreciated