1

I would like to use a timer instead of sleep within a windows service that should perform an action at a constant interval.

Lets say that I have the following class.

class MailManagerClient
{

    //fields
    string someString

    //Constructor
    public MailManagerClient()
    { 
          aTimer = new System.Timers.Timer(30000);
          aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
          aTimer.Enabled = true
    }
    //methode

    public bool DoSomthingIncConstantInterval()
    {
        //Do Somthing
        return true;
    }


    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
       DoSomthingIncConstantInterval()
    }
}

And I also have a windows service with the OnStart method.

I understand that in the OnStart method I will need to start a new thread for the type MailManagerClient.

But how do I start the thread? Which method should be the entry point for the new thread?

How should the thread stay alive?

Brian Gideon
  • 45,093
  • 12
  • 98
  • 145
MoShe
  • 5,523
  • 14
  • 43
  • 71
  • Maybe you should have a look at quartz.net, I think it'll serve your purpose much better. – alxbrd Apr 04 '12 at 15:21
  • Observable.Timer in [System.Reactive.Linq](http://msdn.microsoft.com/en-us/library/hh229435(v=vs.103).aspx) is something else to look into as well. – Austin Salonen Apr 04 '12 at 15:22

3 Answers3

1

In the OnStart method you could have -

MailManagerClient m;
var th = new Thread(()=>m=new MailManagerClient());
th.Start();
ilias
  • 2,330
  • 2
  • 23
  • 33
1

Because you are starting the timer in the constructor than all you really need to do is instantiate a MailManagerClient in OnStart. You do not need to manually create a thread because System.Timers.Timer executes the Elapsed event handler on a thread from the ThreadPool.

public class MyService : ServiceBase
{
  private MailManagerClient mmc = null;

  protected void OnStart(string[] args)
  {
    mmc = new MailManagerClient();
  }

}

I should point out that it would not be obvious to the next programmer looking at your code that MailManagerClient.ctor is actually doing anything. It would be better to define a Start method or something similar that enables the internal timer.

Brian Gideon
  • 45,093
  • 12
  • 98
  • 145
1

You might also consider defining a Windows Task, as explained in this SO answer: What is the Windows version of cron?. The Windows OS will take care of scheduling and threading.

Community
  • 1
  • 1
Philipp Schmid
  • 5,636
  • 5
  • 41
  • 61