0

How can I call my Azure function once on startup and then triggered every 5 minutes after that?

I have a Function that triggers every 5 minutes, during testing it is a pain to wait 5 minutes for it to trigger, so I would like it to trigger once on start up, and then use the every 5 minutes trigger after.

Here is my code

[Function("Function")]
        public async Task Run([TimerTrigger("0 */5 * * * *")] MyInfo myTimer)
        {
            //do stuff

        }

which triggers it every 5 minutes, but not on start up.

Daniel Barnes
  • 163
  • 2
  • 9

2 Answers2

2
[TimerTrigger("0 */5 * * * *", RunOnStartup = true)]

RunOnStartup If true, the function is invoked when the runtime starts. For example, the runtime starts when the function app wakes up after going idle due to inactivity. when the function app restarts due to function changes, and when the function app scales out. Use with caution. RunOnStartup should rarely if ever be set to true, especially in production.

babymilo
  • 101
  • 3
1

Adding to @babymilo answer.

You can make use of RunOnStartup flag to trigger your Function as soon as it starts. Reference

I added RunOnStartup attribute beside my Function and the Function got executed immediately after it was triggered immediately after it started. And then it got triggered again after 5 minutes. RunOnStartup as the name suggests will run or execute your Function once when it starts and then it will execute again at the scheduled time.

My Function.cs:-

using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;

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

Output:-

enter image description here

Reference:-

c# - What is the simplest way to run a timer-triggered Azure Function locally once? - Stack Overflow by BerDev

SiddheshDesai
  • 3,668
  • 1
  • 2
  • 11