Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to implement windows service loop that waits for a period in C# / .NET2.0

My question is that is this the best practice to do this. Couldn't find any good examples. I have following code in file created by VS2005:

public partial class ObjectFolder : ServiceBase
{
    protected override void OnStart(string[] args)
    {
        ObjectFolderApp.Initialize();

        ObjectFolderApp.StartMonitorAndWork();
    }

    protected override void OnStop()
    {
        // TODO: Add code here to perform any tear-down necessary to stop yourservice.
    } 
}

then:

class ObjectFolderApp
{
    public static bool Initialize()
    {
        //all init stuff
        return true;
    }


    public static void StartMonitorAndWork()
    {
        Thread worker = new Thread(MonitorAndWork);
        worker.Start();
    }


    private static void MonitorAndWork()
    {
        int loopTime = 60000;
        if (int.TryParse(_cfgValues.GetConfigValue("OfWaitLoop"), out loopTime))
            loopTime = 1000 * loopTime;

        while (true)
        {
            /* create+open connection and fill DataSet */
            DataSet ofDataSet = new DataSet("ObjectFolderSet");
            using (_cnctn = _dbFactory.CreateConnection())
            {
                _cnctn.Open();

                //do all kinds of database stuff
            }
            Thread.Sleep(loopTime);
        }
    }
}
like image 934
char m Avatar asked Apr 07 '10 15:04

char m


2 Answers

Re-hashing my answer from this question, the recommended way is to use a timer and the following code:

public class MyService : ServiceBase
{
    private Timer workTimer;    // System.Threading.Timer

    protected override void OnStart(string[] args)
    {
        workTimer = new Timer(new TimerCallback(DoWork), null, 5000, 5000);
        base.OnStart(args);
    }

    protected override void OnStop()
    {
        workTimer.Dispose();
        base.OnStop();
    }

    private void DoWork(object state)
    {
        RunScheduledTasks();  // Do some work
    }
}

Simple!

Note that the Timer type being used is System.Threading.Timer, same as Justin specifies.

like image 150
Aaronaught Avatar answered Oct 23 '22 11:10

Aaronaught


Use a System.Threading.Timer to fire the process off at the scheduled interval.

like image 3
Justin Niessner Avatar answered Oct 23 '22 13:10

Justin Niessner