CompEng
CompEng

Reputation: 7376

How can I get my windows service to run at a specific interval?

I want to write a windows service. But it needs to run at specific times. For example, my service should email me every 5 minutes.

private Timer _timer;
private DateTime _lastRun = DateTime.Now;

protected override void OnStart(string[] args)
{
    _timer = new Timer(10 * 60 * 1000); // every 10 minutes
    _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
    //...
}


private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    // ignore the time, just compare the date
    if (_lastRun.Date < DateTime.Now.Date)
    {
        // stop the timer while we are running the cleanup task
        _timer.Stop();
        //
        // do cleanup stuff
        //
        _lastRun = DateTime.Now;
        _timer.Start();
    }
}

I want my service to email me every 5 minutes.

Upvotes: 3

Views: 14349

Answers (8)

Estefany Velez
Estefany Velez

Reputation: 328

For the above said functionality, you can use the combination of console application with windows scheduler.

Schedule your exe to execute every 5 mins. Your exe will email you and stop. Is there anything specific you want to achieve through windows service?

Upvotes: 0

Kieron
Kieron

Reputation: 27107

If you need to do an operation on a timer, then you have two choices

  1. Create a Windows Service and implement some kind of scheduling. This can be complex, so be prepared to that you may spend a lot of time solving issues that have already been solved.
  2. You could setup a scheduled task instead that calls your application.

It all depends how much control you really need.

Upvotes: 1

oleksii
oleksii

Reputation: 35895

Take a look at Quartz.NET or search for "Windows Task Scheduling".

The first approach is programmatic and the later is configuration.

Upvotes: 2

user1518101
user1518101

Reputation: 111

Well I have seen another question which discusses windows service vs scheduled task also this. So you might want to have a look at that other than that here is 2 similar questions which might help:

here too are some great links:

Upvotes: 5

KingCronus
KingCronus

Reputation: 4519

Your code looks good, but did you make a call to timer.start() in the first place during OnStart?

Upvotes: 1

manojlds
manojlds

Reputation: 301037

You might want to use something like Quartz.net in your service. You can then use cron expressions to schedule "jobs" within your service.

Upvotes: 1

HatSoft
HatSoft

Reputation: 11191

The article gives a walkthorugh how to creat windows Service http://msdn.microsoft.com/en-us/library/zt39148a(v=vs.80).aspx

And to run it at a certain time you can set schedule job

Upvotes: 1

Gerald Versluis
Gerald Versluis

Reputation: 33993

Why not just add a timer to your service who does what you want on the interval you configure?

Upvotes: 1

Related Questions