9/11/08

Windows Service - Start Time from app.config, Running Windows Service daily

As for having the app.config data actually "start" the service, you can't really do this. Windows starts the service, or you start the service manually. There's no app.config setting you can put in there to tell the service to start itself.

So a good alternative would be to put in a timer in your service code, and have it pull out the value from the app.config, and run the code you want to run at a particular time when that timer runs out. To do this, you can put a date value in the app.config, and parse it into a datetime in your service. Once you parse it into the datetime, you can then calculate how long it will be until that time comes around, and start either a Thread.Sleep for that amount of time, or set up some kind of timer.



using System.Windows.Forms;


I know this because you're calling a non-parametrized constructor on Timer. Don't use that timer. Use System.Threading.Timer and construct it on your OnStart, while keeping it class level.


You could set a System.Threading.Timer to do the processing work, and have it set the timer each time you start the application. Something like this should work:

using System;
using System.Threading;
public static class Program
{
static void Main(string[] args)
{
// get today's date at 10:00 AM
DateTime tenAM = DateTime.Today.AddHours(10);

// if 10:00 AM has passed, get tomorrow at 10:00 AM
if (DateTime.Now > tenAM)
tenAM = tenAM.AddDays(1);

// calculate milliseconds until the next 10:00 AM.
int timeToFirstExecution = (int)tenAM.Subtract(DateTime.Now).TotalMilliseconds;

// calculate the number of milliseconds in 24 hours.
int timeBetweenCalls = (int)new TimeSpan(24, 0, 0).TotalMilliseconds;

// set the method to execute when the timer executes.
TimerCallback methodToExecute = ProcessFile;

// start the timer. The timer will execute "ProcessFile" when the number of seconds between now and
// the next 10:00 AM elapse. After that, it will execute every 24 hours.
System.Threading.Timer timer = new System.Threading.Timer(methodToExecute, null, timeToFirstExecution, timeBetweenCalls );

// Block the main thread forever. The timer will continue to execute.
Thread.Sleep(Timeout.Infinite);
}

public static void ProcessFile(object obj)
{
// do your processing here.
}
}


Oh, and you would just keep the service running constantly for this. Start the service and forget about it. It'll run your processing every 24 hours on it's own, and always at 10:00 AM, like clockwork.

No comments:

Post a Comment

Welcome