Run NodeJS Cron Jobs in Azure Function App
Sometimes we have a requirement to run some recurring Jobs in our project. For recurring Jobs, we also use the term Cron Jobs.
While choosing any deployment solution we have to keep in mind some points or rather I can say features, one of the major features is that the solution should be economic. Here comes into the picture solution provided by Azure, the Function App which we can configure Hosting as Consumption which is also their Default Hosting plan.
What is Cron?
Cron is a tool to schedule jobs, often referred to as cronjobs. When a job will be executed is controlled by the scheduling expression, a string is split into 5 parts:
- Minute
- Hour
- Day of the month
- Month
- Day of the week
Every minute, Cron can then match the current time against the scheduling expression to detect whether it should execute the command or not.
Below is an Explanation of the Syntax of
Function App
Moving forward Function App provides us with four different types of Triggers, which are
- EventGrid Trigger
- HTTP Trigger
- Queue Trigger
- Timer Trigger
As we are going to leverage Function App to build a solution for Cron Jobs our main focus will be Timer Trigger.
Timer Trigger
Timer Trigger enables us to schedule a task to run at a specified time or interval and that’s what our requirement is.
How we can configure a Timer Trigger?
I am assuming here that you are already familiar with Setting up the Azure Function App project, If not let me know in the comments I will try to cover that out probably in my next article.
Coming back to Configuration Timer Trigger. Configuration of each Function App trigger is pretty straightforward if you look their basic syntax is also the same. Configuration of Function App Model v3 goes in function.json. The Timer Trigger function app looks like this:
{
"bindings": [
{
"name": "timerFunction",
"type": "timerTrigger",
"direction": "in",
"schedule": "0 0 8 1 * *"
}
],
"scriptFile": "../dist/TimerTrigger/index.js"
}
So in the example config I have set the timer to run Every first of the month at 8 am, you can configure it as required.
That’s all after configuring function.json you are all set to run your first Timer Trigger. If you have any queries please let me know in the comments.
PS: Here I have covered almost everything required to create a Timer Trigger in Modelv3. I will shortly try to cover Modelv4 configuration also, stay tuned :)
| Thanks For Reading, Follow Me For More
References
[1] https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-error-pages