user1940031
user1940031

Reputation: 1

How to create service that runs on a timer to query an external web service?

I am a little overwhelmed with the possibilities and best way to handle this. I need to have a web service hosted on Windows Azure that runs a timer and after elapsed time expires will query an external web service and process the data retrieved and import it into my SQL Azure database. I currently am hosting a WCF Web Service and a Website on Windows Azure along with a SQL Azure database. I tried a worker role, but that just runs one time and quits after the Run method finishes, even if you add a timer and start the timer with an interval. Best solution is appreciated! Thanks.

Upvotes: 0

Views: 617

Answers (1)

Gaurav Mantri
Gaurav Mantri

Reputation: 136286

The trick is have the worker role NEVER come out of "Run" method ever. Something like:

    public override void Run()
    {
        while (true)
        {
            Thread.Sleep(10000);
        }
    }

Now coming to your question, you could simply implement a Timer object in your worker role and when the timer elapses, you make a call to that external web service. You could implement your own timer using following code:

    public override void Run()
    {
        System.Timers.Timer timer = new System.Timers.Timer(1000);
        timer.Elapsed += timer_Elapsed;
        while (true)
        {
            Thread.Sleep(10000);
        }
    }

    void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        //Execute the code to call the web service
    }

However for implementing timers, my favorite is Quartz library (http://quartznet.sourceforge.net/). I found it fairly easy to use and quite flexible plus it's open source.

Hope this helps.

Upvotes: 2

Related Questions