views:

52

answers:

4

I need to write some .NET code that runs on a regular interval to check for "unprocessed" items in a table in the database, processes them, and then writes back to the database that they are processed. We'll probably set it up to run every minute.

How can I set up in the component in a Windows Server environment so that the code executes on a periodic basis?

+3  A: 

Use System.Timers.Timer in your windows service.

You can have such a code (from MSDN) in your windows service OnStart event :

// Hook up the Elapsed event for the timer.
timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

// Set the Interval to 2 seconds (2000 milliseconds).
timer.Interval = 2000;
timer.Enabled = true;

...........

// Specify what you want to happen when the Elapsed event is raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
    ......
}

If the interval is not frequent for example if it runs daily also consider using Windows Task Scheduler. It can run your application for the given interval (note if that interval is not so frequent).

Incognito
Any reason for down vote ???
Incognito
+2  A: 

Windows Scheduled Tasks (start-programs-accessories-system tools)... SSIS Job Scheduling... 3rd Party Job Software (Activebatch, etc)...

Fosco
+3  A: 

Create a scheduled task through the Windows Task Scheduler. The scheduled task would then run your compiled .NET EXE (I'm assuming it's an EXE) on a periodic basis. If you need it to run shorter than a minute, I think you then need to move to a windows service.

Here's a nice tutorial on how to set up a scheduled task. The screen shots are from Windows XP.

David Hoerster
+1  A: 

You can either set it up as a service with a timer which goes off whenever you want (for this frequency, probably your best option) or you can set up a scheduled task in Windows Scheduler.

If you're going with the windows service route, your Start() method will look something like:

Timer tmr = new Timer(60000, true) //this could be wrong: set it for one minute and turn on auto-reset.

tmr.Start();

Then you'll have an event handler to handle the Timer's event (can't remember the name right now: Tick, maybe?) which will call your actual code.

If your code takes longer than a minute to complete, you might set auto-restart to false and then re-enable your timer when the processing protion hands control back to the service.

AllenG