Create scheduled jobs with azure functions

In today article we will make use of azure feature called Azure Function Applications. This type of application uses server-less functions to execute code without setting up whole machine. 10^6 function executions per month are free and then next bulk cost like 15 cents, which is cheap. The best part is that function can have multiple defined triggers, configurable in azure.

We will build application that will send mail with report at start of every business day. Why? Because everyone loves to read reports… We will make use of “timer” trigger that lets you run a server-less function that is deployed to azure on a user defined schedule. In our case from Monday to Friday at 8:30 UTC. Whole application is hosted also on GitHub

App creation procedure can fit in these steps:

  1. Create a new project
  2. Creating application logic
  3. Deploy application to azure

1. Create a new project

Perquisites: visual studio, storage emulator, azure account to deploy application

2. Creating application logic

Defining the trigger
We want to execute trigger at 8:30 local time every working day from Monday to Friday. CRON expression is expressed in format {second} {minute} {hour} {day} {month} {day-of-week}. So, in my case that is “0 30 8 * * 1-5”

[FunctionName("SendReport")]
public static void Run([TimerTrigger("0 */2 * * * *")]TimerInfo myTimer, ILogger log)
{
    // Format: {second} {minute} {hour} {day} {month} {day-of-week}.
    // 0 */2 * * * * => run every 2 min
    // 0 30 8 * * 1-5 => run from Monday to Friday at 08:30 AM

    SendReportEmail(log).Wait();

    log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
}

The default time zone used with the CRON expressions is Coordinated Universal Time (UTC). Therefore, do not forget to include WEBSITE_TIME_ZONE to azure application settings in case that you are living in different time zone than GMT 0. For me that is “Central Europe Standard Time”. For full list go check msdn ref.

Sending an email
I choose to use SendGrid API. They have good library for .net core that can be consumed by our application. In case you would like to use same API, all you need to do is register on their page SendGrid and then create API key. Then install SendGrid NuGet package to .net application and specify API key that we created in their portal.

private static async Task SendReportEmail(ILogger log)
{
    var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");

    var client = new SendGridClient(apiKey);
    var from = new EmailAddress("reportmaker@reportmaker.com");
    var to = new EmailAddress("reportreciever@reportreciever.com");
    var subject = "Here is your daily report.";
    var htmlContent = "Wow such report, such fun.";
    var msg = MailHelper.CreateSingleEmail(from, to, subject, null, htmlContent);

    var response = await client.SendEmailAsync(msg);

    if (response.StatusCode != HttpStatusCode.Accepted ||
        response.StatusCode != HttpStatusCode.OK)
    {
        log.LogError("Send email failed.");
    }
}

Test application locally
In case there are no build errors you just hit F5 and the application should download all its dependencies (Azure functions CLI tools) and automatically start azure storage emulator on the background. Application will use windows console as output by default. We can see function executions there as on the picture bellow.

3. Deploy application to azure
Right click on solution and select publish. We are deploying for the first time, this process will create application in azure for us.

Choose your subscription and edit the fields if you would like, their meaning is intuitive by the labels.

In case you encounter error while publishing “Web deployment task failed. (Web Deploy cannot modify the file ‘YourProjectName.dll’ on the destination because it is locked by an external proces.“ set MSDEPLOY_RENAME_LOCKED_FILES = 1 in application settings. This is known bug at the time I am writing this article.

Your application will be created under “Function App” as on picture bellow.

Leave a Reply

Your email address will not be published. Required fields are marked *