2

Move CRON Expression from Hard Code to Configuration in Azure Function App

 2 years ago
source link: https://edi.wang/post/2022/9/13/move-cron-expression-from-hard-code-to-configuration-in-azure-function-app
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

img-d6b4c65d-59bc-4f55-bec6-28811da31d99.png

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". 

img-b931d5f9-7f8f-4d2e-8754-375bff7cffff.png

Observe the function log to make sure it works

img-b4433146-2017-4c56-98e4-a0559b9b6604.png

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK