7
votes

I'm doing an Azure Function that is timer triggered. I want to be able to change the timer, i.e the cron expression, without having to do a re-deploy. I'm getting my other settings from an App Configuration in Azure but this doesn't work for the TimerTrigger and I get : An object reference is required for the non-static field, method or property when I write TimerTrigger(config["CronExpression"]) where config is an IConfiguration. Does anyone know how to do this with Azure App Configuration? I wish to not use a settings.json file other than for local development

2

2 Answers

7
votes

You can specify the timer expression in your configuration by referencing the name surrounded by %...%. For example, in your configuration create a new value with a name of MyTimerExpression and value of, for example, 0 */10 * * * * to run every 10 minutes. In your local development environment, that means adding an entry into the local.settings.json file like this:

    {
        ...
        "MyTimerExpression": "0 */10 * * * *"
        ...
    }

Now in your timer trigger, do this:

    [TimerTrigger("%MyTimerExpression%")]
1
votes

Quick Answer

You can specify the timer expression in your configuration by referencing the name surrounded by %...%.

schedule / ScheduleExpression:

A CRON expression or a TimeSpan value. A TimeSpan can be used only for a function app that runs on an App Service Plan. You can put the schedule expression in an app setting and set this property to the app setting name wrapped in % signs, as in this example: "%ScheduleAppSetting%".

~ https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-timer?tabs=csharp#configuration

Research

It's not mentioned in the xml doc for the TimerTriggerAttribute https://github.com/Azure/azure-webjobs-sdk-extensions/blob/a34f4909bad85ebdb7777b2fe8a823d879f3c48d/src/WebJobs.Extensions/Extensions/Timers/TimerTriggerAttribute.cs#L21-L24

However, TimerSchedule Create uses a name resolver https://github.com/Azure/azure-webjobs-sdk-extensions/blob/9feb4f2ad6f70e443a036a135b58121c70dbdaf3/src/WebJobs.Extensions/Extensions/Timers/Scheduling/TimerSchedule.cs#L65

... which has the logic in to parse out %...% values https://github.com/Azure/azure-webjobs-sdk/blob/b798412ad74ba97cf2d85487ae8479f277bdd85c/src/Microsoft.Azure.WebJobs.Host/NameResolverExtensions.cs#L56-L72

... which is then used by the DefaultNameResolver to get a value from configuration https://github.com/Azure/azure-webjobs-sdk/blob/aeabc5f43f7c50ca67267cbfa429a08fc68623a9/src/Microsoft.Azure.WebJobs.Host/DefaultNameResolver.cs#L34


Thanks to https://stackoverflow.com/a/58979319