Creating cron jobs with Azure

Saran
3 min readApr 3, 2021

--

I recently had a to create a simple cron job where a script which uses a headless browser performs some task needed to be executed at certain times of a day. It took me a couple of hours to write the script and when I had to deploy it up in the cloud I had to choose between either having a bash script inside a virtual machine and run a cron or go with a Faas approach. Since the virtual machine approach seemed like a over kill and wallet driller, I went with the new chick in town, the serverless way. In the rest of the article I will be explaining how to work with Timer Trigger functions on Azure.

This article assumes that you have installed Nodejs, Azure extension in your VS Code and you have a local azure function project setup.

Click on “Add Function …”. Select Timer Trigger, a name for you function and a cron expression. A cron expression is just a string of specific format that specifies when to run the task. Azure uses NCronTab library to interpret NCRONTAB expressions.

Example of a cron expression: 0 */5 * * * * — 12 times an hour — at second 0 of every 5th minute of every hour of each day.

Once you are done with this wizard you can find a folder with files for your function. If you want to install npm packages just install them. Modify the .vscode > settings.json as following and add node_modules folder to .funcignore. The reason we are doing this is to reduce the deploy time. Azure VS Code extension runs “npm install” locally and deploy the app package. For remote build we add "azureFunctions.scmDoBuildDuringDeployment": true

{"azureFunctions.deploySubpath": ".","azureFunctions.projectLanguage": "JavaScript","azureFunctions.projectRuntime": "~3","debug.internalConsoleOptions": "neverOpen","azureFunctions.scmDoBuildDuringDeployment": true}

For this article our function is just gonna use a logger package called Ayiooo that I wrote a month ago and log “hey” in my discord server every 5 mins. So my cron expression would look something like “0 */5 * * * *”.

npm install ayiooo

This is how my index.js file of my function looks like.

Now that all our function setup is done locally we can run func start to test it locally. If everything is good we can proceed to create a function app on our azure portal. Have a look at this if you are stuck. I personally prefer a Linux consumption function app.

Now just click on your function from the azure extension and click on “Deploy to function app”.

And done! The tricky part for me was to figure out how to handle the package installation, node_modules and reduce deploy time since most of the resources online were for .NET. Hope it helps 🍭

--

--

Saran

Likes to talk about distributed systems, blockchain and the web. Logs his understandings in this digital garden so he can find them if in case he forgets.