DEV Community

Cover image for How to debug a Time Trigger Azure Function Locally
Emanuele Bartolesi
Emanuele Bartolesi

Posted on

How to debug a Time Trigger Azure Function Locally

Very often I have to develop timer triggered Azure Function with C#.
To optimize the development time, of course, it is not possible to wait every time the timer (especially if the timer is every morning at 7:00AM πŸ™‚).

Let's see how we cannot waste our time waiting the trigger but launch an Azure Function time triggered instantly.

Solution

The default method of an Azure Function has a parameter called "RunOnStartup" hidden by default.
If you want to run the Azure Function at the startup, set it to true and launch the debug session again.

[FunctionName("Function1")]
public void Run([TimerTrigger("0 */5 * * * *", RunOnStartup = true)]TimerInfo myTimer, ILogger log)
{
    log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
}
Enter fullscreen mode Exit fullscreen mode

By the way, in this case the function will be launched also in the production environment when you restart the Azure Function or when you deploy a new version of the function.
To prevent that, you can use the conditional compilation directive in the function method.

#if DEBUG
     RunOnStartup= true
#endif
Enter fullscreen mode Exit fullscreen mode

Below you can find the full code with the compilation directive for the debug exception.

[FunctionName("Function1")]
public void Run([TimerTrigger("0 */5 * * * *", 
#if DEBUG
     RunOnStartup= true
#endif    
)]TimerInfo myTimer, ILogger log)
{
    log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!
Happy debugging. 🦸

Discussion (0)