Question

I am trying to validate the solution I came up for what I think is a fairly typical problem. I have a service running and every 10 minutes it should do something. I've ended up with the following:

private AutoResetEvent autoResetEvent = new AutoResetEvent(true);
private bool isRunning = true;

public void Execute()
{
    while(isRunning)
    {
       DoSomething();

       if(isRunning)
       {
         autoResetEvent.WaitOne(new Timespan(0, 10, 0));
       }
    }
}

public void Stop()
{
    isRunning = false;
    autoResetEvent.Set();
}

The immediate potential problems I can see is that I'm not doing any sort of locking around the isRunning modification in Stop() which gets called by another thread but I'm not sure I really need to? The worst that I think could happen is that it runs one extra cycle.

Beyond that are there any obvious problems with this code? Is there a better way to solve this problem that I'm unaware of?

Was it helpful?

Solution

You could try using a System.Threading.Timer:

Timer tmr = new Timer(DoSomething, null, new TimeSpan(0, 0, 0), new TimeSpan(0, 10, 0))

OTHER TIPS

This won't run every 10 minutes; it will be very close to every 10 minutes if DoSomething is a quick process. The next run will happen 10 minutes afterDoSomething completes.

You could use a job scheduler like Quartz.Net.

One better way is to use something like Windows Server AppFabric, which has notions of recurring tasks, error handling, and management built in. You just write the actual code you need. Unfortunately, it's bleeding edge today, but it's what I would choose for new development of this kind.

What about using Windows Workflow Foundation? I think its quite oriented to that kind of tasks.

You can could start the appruntime through your program, and then let the WWF app take care of things.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top