Problem


When creating Azure Function with Timer trigger, we usually write CRON expression like [TimerTrigger("*/2 * * * *")] in our function code. It works most of the case, but when you need to dynamically adjust your timer based on business needs, you will have to update your code and redeploy the function, which may not be so easy in an enterprise application.

Let's see how can we remove the hard code CRON expression and put it into configuration that we can easily update on the Azure Portal without redeploy the code.

Solution


In my case, I created a function that will execute every 2 minutes to send email notifications. The CRON expression is hard coded as */2 * * * *

[FunctionName("NotificationV2")]
public async Task Run([TimerTrigger("*/2 * * * *")] TimerInfo myTimer, ILogger log)
{
    log.LogInformation($"NotificationV2 Timer trigger function executed at UTC: {DateTime.UtcNow}");
    // logic ...
}

To make it reading values from configuration, we need to first create a local.settings.json file if you don't have one. This is typically already created by VS or the Azure Function tools. It is just for local development use. 

Then, add a key and value in "Values" node, which represents the CRON expression. In my case, I use "NotificationV2CRON" with "*/2 * * * *"

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "NotificationV2CRON": "*/2 * * * *"
  }
}

Now, change the original code to %NotificationV2CRON%

[FunctionName("NotificationV2")]
public async Task Run([TimerTrigger("%NotificationV2CRON%")] TimerInfo myTimer, ILogger log)
{
    log.LogInformation($"NotificationV2 Timer trigger function executed at UTC: {DateTime.UtcNow}");
    // logic ...
}

Run your code and test if it works

Deploy your code to Azure. Then go to "Configuration" tab under your Azure Function App. Add a new application settings with the name of your CRON expression, in my case "NotificationV2CRON". 

Observe the function log to make sure it works

Now you will be able to update the CRON value on the fly within a few mouse click in Azure Portal!