Windows Polling Agent Service

-------------------------------------------------------
Goto blog home
Visit my new blog dedicated to Internet of Things, Embedded Programming & Automation
-------------------------------------------------------
In this article the basic framework to write a polling agent as a windows service has been explained. The poller is hosted as a windows service (out of scope of this article), and the poller itself is designed to start up at regular intervals of time and perform a designated activity. The polling mechanism is defined in the 'PollerWorker' function below. Bootstrapping into this PollerWorker function has been accomplished using a Timer object in the service OnStart function. A global variable _keepRunning has been used to break out of the PollerWorker function when the service is manually stopped from the Windows Service Console Manager.

public partial class PollerAgent: ServiceBase
{
Timer _objTimer = new Timer();
bool _keepRunning;
public PollerAgent()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
// TODO: Add code here to start your service.
_keepRunning = true;
_objTimer.Elapsed += new ElapsedEventHandler(PollerWorker);
_objTimer.Interval = 300000;
_objTimer.Enabled = true;
}
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
_keepRunning = false;
_objTimer.Enabled = false;
}
private void PollerWorker(object source, ElapsedEventArgs e)
{
while (_keepRunning == true)
{
//Write code to perform polling activities here

//Suspend the current execution thread
//Polling will resume again after specified amount of time
System.Threading.Thread.Sleep(300000);
}
}
}

No comments:

Post a Comment