Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Create Scheduled Azure Web Jobs

Today I’m talking about Scheduled Azure Web Job.

Azure Web Job is a very nice way to run your code inside a cloud based environment.

Azure WebJobs provide an easy way to run scripts or programs as background processes in the context of an App Service web app, API app, or mobile app. You can upload and run an executable file such as as cmd, bat, exe (.NET), ps1, sh, php, py, js and jar. 

https://docs.microsoft.com/en-us/azure/app-service-web/websites-webjobs-resources

I often use this way to create scheduled job to manage user alerting, to check the data consistence of my SharePoint Online data, in other words to run my .Net code without having to worry of where and how my code is hosted and executed.

Create an Azure Web Job is very simple: you can create a simple .Net Console Application and deploy it as an Azure Web Job.
In this example, I’ll reuse the code taken from this post of mine thanks to which I can send an email using Office365 SMTP.

http://zsvipullo.blogspot.it/2015/01/send-e-mail-message-using-office365.html

Then, my totally useless application will send an email with the current date and time inside the mail subject. This .Net code will run inside an Azure App Service.

Here the code:

usingSystem;
usingSystem.Net.Mail;

namespacezSvipulloAzureJob
{
    class Program
    {
        static voidMain(string[] args)
        {
            try
            {
                Console.WriteLine("Sending message...");
                sendMailUsingOffice365SMTP();
                Console.WriteLine("...Message sent");
            }
            catch (Exception ex)
            {
                //Here the business logic to manage the exception

                //****************************************************
                //You have to rethrow the exception in order to
                //View the Failed Status inside the Azure Portal
                //****************************************************
                throw;
            }
        }

        private static voidsendMailUsingOffice365SMTP()
        {
            //Creating a new mail message
            MailMessagemessage = new MailMessage();

            //Adding recipients
            message.To.Add(new MailAddress("[email protected]", "Gino"));

            //Adding Subject
            message.Subject = "This is the Subject line " + DateTime.Now.ToString("u");

            //Adding sender
            message.From = new MailAddress("[email protected]", "Sergio Russo");

            //Adding body text
            message.Body = "This is the message body";

            //Configuring SMTP
            SmtpClient smtp = new System.Net.Mail.SmtpClient("outlook.office365.com");
            smtp.EnableSsl = true;
            smtp.Port = 587;
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

            //Setting credentials
            //IMPORTANT!!! You must use your tenant crendential using the email address format and NOT the domain username
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = newSystem.Net.NetworkCredential("[email protected]", "wlamu$$a.1");

            //Sending message
            smtp.Send(message);
        }
    }
}

Now we have to publish the console application as Azure Web Job, choosing the Publish as Azure Web Job command within the solution explorer, by right clicking on your project.



As Web Job Run Mode you have to choose Run on Demand.

Azure Web Job is part of an App Service: you must create a new App Service or select an Existing App Service in order to deploy your job.

Follow the wizard in order to publish your job.

Once the job has been published, you can see it inside the Azure Portal, finding your App Service, Web Jobs.



By clicking in the Run button, your Web Job is executed!



Using the Log button you can see the detail of the execution: here you can see all the messages written inside your console application.



As written in the code comments, you have to rethrow any exception in order to see the Failed status in the Azure Portal console.

And up to far so simple I would say ...

Now we have to schedule this job: in the past, you could create an Azure Scheduler Jobs which runs periodically your Web Job.

This solution has been deprecated an if you try to do this using the documented way using webjob-publish-settings json file with a configuration like this does not work:

{
  "$schema": "http://schemastore.org/schemas/json/webjob-publish-settings.json",
  "webJobName": "xxxx",
  "startTime": "2016-04-01T00:00:00+01:00",
  "endTime": null,
  "jobRecurrenceFrequency": "Hour",
  "interval": 1,
  "runMode": "Scheduled"
}

This way is deprecated and cause the Visual Studio crash publishing the job.

The right solution is to create a settings.job file that will contain a cron expression which tell to the system the schedule information.

Here the content:

{
  "schedule": "0 * * * * *"
}

In this case the job will be executed every minutes.

The CRON expression is composed of 6 fields: {second} {minute} {hour} {day} {month} {day of the week}.

This file must be placed in the project root folder and must be marked as Copy always or Copy if newer in order to copy the file in the build directory.



Republishing the project with this new setting file and navigating the Azure Portal, I can see that the Schedule field contains my Cron Expression.


This job will be executed every 1 minute.

Note: you App Service MUST HAVE the Always On configuration flat set to On: by default this configuration is set to Off.



If you don’t set this configuration, your scheduled task will not run because the app service application pool is unload if idle.

Always Onconfiguration is not available on free App Service!!!




This post first appeared on ZSvipullo, please read the originial post: here

Share the post

Create Scheduled Azure Web Jobs

×

Subscribe to Zsvipullo

Get updates delivered right to your inbox!

Thank you for your subscription

×