1
votes

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?

3
Maybe you should have a look at quartz.net, I think it'll serve your purpose much better. - alxbrd
Observable.Timer in System.Reactive.Linq is something else to look into as well. - Austin Salonen

3 Answers

1
votes

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.

1
votes

In the OnStart method you could have -

MailManagerClient m;
var th = new Thread(()=>m=new MailManagerClient());
th.Start();
1
votes

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.