views:

137

answers:

4

I am making a Windows service which needs to continuously check for database entries that can be added at any time to tell it to execute some code. It is looking to see if it's status is set to pending, and it's execute time entry is > than the current time. Is the only way to do this to just run select statements over and over? It might need to execute the code every minute which means I need to run the select statement every minute looking for entries in the database. I'm trying to avoid unneccesary cpu time because I'm probably going to end up paying for cpu cycles on the hosting provider

+1  A: 

Given you talk about the service provider, I suspect one of the main alternatives will not be open to you, which is notification services. It allows you to register for data changed events and be notified, without the need to poll the database. It does however require service broker enabled for it to work, and that potentially could be a problem if it is hosted - some companies keep it switched off.

The question is not tagged to a specific database just SQL, the notification services is a SQL Server facility.

Andrew
It might be easier to find a provider that allows notification servers than get a provider where I need a vm which can host a windows service. I haven't chosen a provider yet
JonF
A: 

If you're using SQL Server and open to a different approach, check out SQL Server Notification Services.

Austin Salonen
A: 

Oracle also provides notifications, the call it Database Change Notification

rwhit
A: 

Be aware that Notification Services is only for SQL 2005, and has been dropped from SQL 2008.

Rather than polling the database for changes, I would recommend writing a CLR stored procedure that is called from a trigger, which is raised when an appropriate change occurs (e.g. insert or update). The CLR sproc alerts your service which then performs its work.

Sending the service alert via a TCP/IP or HTTP channel is a good choice since you can deploy your service anywhere, just by modifying some configuration parameter that is read by the sproc. It also makes it easy to test the service.

I would use an event driven model in your service. The service waits on an auto-reset event, starting a block of work when the event is raised. The sproc communications channel runs on another thread and sets the event on each incoming request.

Assuming the service is doing a block of work and a set of multiple pending requests are outstanding, this design ensures that those requests trigger just 1 more block of work when the current one is finished.

You can also have multiple workers waiting on the same event if overlapping processing is desired.

Note: for external network access the CREATE ASSEMBLY statement will require the PERMISSION_SET option to be set to EXTERNAL_ACCESS.

devstuff