Send a web request to a Web Site periodically using Azure Mobile Services

Mobile Services

Today I’m facing a new challenge with IIS (Internet Information Service) of one of my Web Site on Windows Azure. As you probably know, after a few minutes of inactivity, IIS will go take a nap and will wake up at the next incoming request. It means after about 15 – 20 minutes, if your web site did not receive any incoming request it will pause itself. And the following request will take longer because the web server needs to start. It can be a problem for the guests visiting your web site or consuming your services. One solution is to use Windows Azure Mobile Services and more precisely the Scheduler feature.

Just to remind you, Azure Mobile Services is free, up to 10 services, using shared instances. So let’s use it!

Create the Windows Azure Mobile Service

Mobile Services

On your Azure management page, click NEW | COMPUTE | MOBILE SERVICE | CREATE.

Mobile Services

Enter the DNS name you want to use to identify your service. Then select a database or create a new one if you don’t have one. If you don’t need the database (like if you don’t want to use the Mobile Service other than the scheduler we’re going to create) I’ll show you how to delete this database so you don’t have to pay for it.

Mobile Services

On this new screen, enter the name of your new database, a user and the password.

Mobile Services

The service is creating… It should take less than a minute.

You don’t need the database? Let’s delete it.

Mobile Services

In the list of SQL Databases you have, select the database you’ve just created and click the DELETE button. If you have only one database on the SQL Server, you’ll be ask if you want to delete the server too. If you don’t need it, simply answer Yes.

Create the Scheduler.

Mobile Services

Go back to the Mobile Service you’ve just created. Click on SCHEDULER then CREATE A SCHEDULED JOB.

Mobile Services

Enter a name to identify the name of the job. Select the schedule. On the picture above, I want to run the script every 15 minutes.

Mobile Services

Here we go, the last step in the creation of the scheduler is to write the script that will send a request to our web site. I’m adding a very little bit of JavaScript to log into the Console if an error happens. You can copy / paste the code bellow. Then click ENABLE to run the script on your schedule.

var url = "http://www.fabienlavocat.com";
var request = require('request');

request(url, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log('Contact ' + url + ' OK');
        } else {
            console.error('Error trying to contact ' + url);
        }
});

Mobile Services

If you go back to your service, click on LOGS, you’ll see that the script has run.