Introduction
In this article, we will learn about schedule background tasks using Time-Triggered Azure Functions.
Time Trigger Azure Function helps us to run a particular task or job at a specific mentioned time. So in another way, we can treat this function for background processing jobs. It can help you run a characteristic on a configurable agenda. In contrast to HTTP-induced Azure features, CRON expression (timing information) is saved in an Azure storage account after which is passed to the characteristic on execution. As an end result, after you upload in a timer-triggered function for the first time, there can be some extra steps needed to run your function app-venture domestically.
Source Code - Github
Table of Contents
- Project Setup
- What we are going to Build?
- Table Schema - SQL Database
- What is CRON expression?
- Configure the CRON expression
- Configure the Functions
- Disabling a Function
- Testing the Functions
- Summary
Project Setup
- Open Visual Studio and search for Azure Functions in the search bar. Click on the Next button
- Define the project name and path to save the file. Click on Create
Choose the target framework and make sure to select the Time Trigger in the below options and by default, the function will take the 5 min Cron expression if you want to change you can change it in the right side menu. See the picture below
What we are going to Build?
So we are going to have two functions in which one function will run for every 1 minute to save the data to the database and another function will pull the data from the database for every 5 min
- Insert Data - Every 1 Minute
- Fetch Data - Every 5 Minute
Table schema - SQL Database
Create the Table in the database as per the below script where it consists of the basics details Name, IsActive, AddMinutes columns.
USE [SampleDB]
GO
/****** Object: Table [dbo].[Employees] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Employees](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](max) NULL,
[IsActive] [bit] NOT NULL,
[AddMinutes] [datetime] NULL,
CONSTRAINT [PK_Employees] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
We have a table in the database and let's set up the SQL configuration in the Azure function. Create a folder named Models in which we will create a class named Employee with all the fields that are existing as per the table in the database.
Employee.cs
using System;
namespace TimeTrigger_AzureFunction.Models
{
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
public DateTime AddMinutes { get; set; }
}
}
Now set up the DbContext to our application. This helps us to access the Database tables which will be generated by our Models via the application. Create a class named AppDbContext for setting up the EF Core Transactions
AppDbContext.cs
using Microsoft.EntityFrameworkCore;
using TimeTrigger_AzureFunction.Models;
namespace TimeTrigger_AzureFunction
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<Employee> Employees { get; set; }
}
}
In order to make a connection to SQL Database with EF Core here, we require the following packages to establish the connection by using the Db first approach. We can install the required packages by using the Nuget Package Manager or by using the Package manager console.
Make sure you install the package with version v2.0.0 because that is the fully working version without any issues with v2 Net Core.
Create a Class named Startup.cs to integrate the Dependency Injection. In our Startup class, we use the FunctionsStartup
attribute on the assembly to indicate a startup class that will run when the function app starts. In that class, which inherits FunctionsStartup
then we override the Configure
method.
Startup.cs
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
[assembly: FunctionsStartup(typeof(TimeTrigger_AzureFunction.Startup))]
namespace TimeTrigger_AzureFunction
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
string connectionString = "Data Source=********;Integrated Security=true;Database=SampleDB";
builder.Services.AddDbContext<AppDbContext>(
options => SqlServerDbContextOptionsExtensions.UseSqlServer(options, connectionString));
}
}
}
What is CRON Expression?
Let us first understand the CRON expression includes six parts - second, minute, hour, day, month, and day of the week in Azure Function, and every element is separated with the aid of using space. We can specify the subsequent unique characters within the expression.
- A comma (,) is used to specify the listing of values
- A ahead slash (/) is used to reoccurs execution time
- An asterisk (*) suggests that the expression could have any value
- A hyphen (-) suggests a number of values
Sample examples of CRON Expressions
Image Courtesy: Working With Timer-Triggered Azure Functions
Configure the CRON expression
By default when setting up the project the function will have the 5 min trigger expression in the code itself. So it's very hard to maintain this expression in class files to avoid these we can declare a variable in the local.settings.json file and attach the respective CRON expression and use those variables in C# code and this makes our life easy while maintaining multiple items. In this file, as we mentioned earlier that we are going to add two expressions one is for every 5 minutes and another one is for every 1 minute.
See the code below,
local.settings.json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
//CRON Expression -
"EveryFiveMinutes": "0 */5 * * * *",
"EveryMin": "0 */1 * * * *"
}
}
Configure the Function methods
let's add the AppDbContext as the Constructor Injection in which we can consume the respective tables to perform the Entity Framework Transactions and add the two functions for adding and fetching the data from the Database. The time trigger expression is fetching from the local.settings.json file and now the two functions have been configured and once you run the Azure function the respective tasks will perform with their timelines.
Function1.cs
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using TimeTrigger_AzureFunction.Models;
namespace TimeTrigger_AzureFunction
{
public class Function1
{
#region Property
private readonly AppDbContext _appDbContext;
#endregion
#region Constructor
public Function1(AppDbContext appDbContext)
{
_appDbContext = appDbContext;
}
#endregion
[FunctionName("JobExecution")]
public void InsertData([TimerTrigger("%EveryMin%")] TimerInfo myTimer, ILogger log)
{
var employee = new Employee { Name = "Jay", IsActive = true,AddMinutes = DateTime.Now};
_appDbContext.Employees.AddAsync(employee);
_appDbContext.SaveChangesAsync();
log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
}
[FunctionName("FetchResults")]
public void FetchData([TimerTrigger("%EveryFiveMinutes%")] TimerInfo myTimer, ILogger log)
{
var data = _appDbContext.Employees.ToList();
log.LogInformation($"Total Records Count : {data.Count}");
}
}
}
Disabling a Function
A habitual feature execution may be particularly disruptive whilst attempting to check or debug an unrelated issue, so it is able to additionally be useful to disable your timer-triggered feature. To disable the feature, replace local.setting.json with a brand new key for AzureWebJobs.Disabled set to “true” as a default:
//To disable a specific Funtion from executing
"AzureWebJobs.FetchResults.Disabled": "true",
Testing the Functions
Run the project and it will run with a storage emulator in the background and in the command prompt we can see the results of the jobs.
Summary
In this article, we learned how to implement the background jobs/scheduled tasks using the Time-triggered Azure Functions and integrating with the Database by using the Entity Framework Core Dependency Injection. I hope this article helps you.
Thank you for reading, please let me know your questions, thoughts, or feedback in the comments section. I appreciate your feedback and encouragement.
Keep learning....!