Azure

Time Triggered Azure Features – A Information To Background Duties Utilizing C#

Introduction

On this article, we are going to find out about schedule background duties utilizing Time-Triggered Azure Features.

Time Set off Azure Operate helps us to run a selected activity or job at a selected talked about time. So in one other manner, we will deal with this perform for background processing jobs. It may show you how to run a attribute on a configurable agenda. In distinction to HTTP-induced Azure options, CRON expression (timing data) is saved in an Azure storage account after which is handed to the attribute on execution. As an finish outcome, after you add in a timer-triggered perform for the primary time, there may be some additional steps wanted to run your perform app-venture domestically.

Supply Code – Github

Desk of Contents

  1. Venture Setup
  2. What we’re going to Construct?
  3. Desk Schema – SQL Database
  4. What’s CRON expression?
  5. Configure the CRON expression
  6. Configure the Features
  7. Disabling a Operate
  8. Testing the Features
  9. Abstract

Venture Setup

  • Open Visual Studio and seek for Azure Features within the search bar. Click on on the Subsequent button
  • Outline the venture title and path to save lots of the file. Click on on Create

Select the goal framework and ensure to pick out the Time Set off within the beneath choices and by default, the perform will take the 5 min Cron expression if you wish to change you possibly can change it in the fitting facet menu. See the image beneath

Time Triggered Azure Functions - A guide to background tasks using C#

What we’re going to Construct?

So we’re going to have two features wherein one perform will run for each 1 minute to save lots of the info to the database and one other perform will pull the info from the database for each 5 min

  1. Insert Knowledge – Each 1 Minute
  2. Fetch Knowledge – Each 5 Minute

Desk schema – SQL Database

Create the Desk within the database as per the beneath script the place it consists of the fundamentals particulars Title, IsActive, AddMinutes columns.

USE [SampleDB]
GO
/****** Object:  Desk [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

Time Triggered Azure Functions - A guide to background tasks using C#

Now we have a desk within the database and let’s arrange the SQL configuration within the Azure perform. Create a folder named Fashions wherein we are going to create a category named Worker with all of the fields which can be present as per the desk within the database.

Worker.cs

utilizing System;

namespace TimeTrigger_AzureFunction.Fashions
{
    public class Worker
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public bool IsActive { get; set; }
        public DateTime AddMinutes { get; set; }
    }
}

Now arrange the DbContext to our software. This helps us to entry the Database tables which might be generated by our Fashions through the applying. Create a category named AppDbContext for organising the EF Core Transactions

AppDbContext.cs

utilizing Microsoft.EntityFrameworkCore;
utilizing TimeTrigger_AzureFunction.Fashions;

namespace TimeTrigger_AzureFunction
{
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> choices)
        : base(choices)
        {

        }
        public DbSet<Worker> Staff { get; set; }
    }
}

As a way to make a connection to SQL Database with EF Core right here, we require the next packages to determine the connection through the use of the Db first method. We will set up the required packages through the use of the Nuget Bundle Supervisor or through the use of the Bundle supervisor console.

Be sure to set up the package deal with model v2.0.0 as a result of that’s the totally working model with none points with v2 Internet Core.

Time Triggered Azure Functions - A guide to background tasks using C#

Create a Class named Startup.cs to combine the Dependency Injection. In our Startup class, we use the FunctionsStartup attribute on the meeting to point a startup class that can run when the perform app begins. In that class, which inherits FunctionsStartup then we override the Configure technique.

Startup.cs

utilizing Microsoft.Azure.Features.Extensions.DependencyInjection;
utilizing Microsoft.EntityFrameworkCore;
utilizing Microsoft.Extensions.DependencyInjection;

[assembly: FunctionsStartup(typeof(TimeTrigger_AzureFunction.Startup))]
namespace TimeTrigger_AzureFunction
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            string connectionString = "Knowledge Supply=********;Built-in Safety=true;Database=SampleDB";
            builder.Providers.AddDbContext<AppDbContext>(
                choices => SqlServerDbContextOptionsExtensions.UseSqlServer(choices, connectionString));
        }
    }
}

What’s CRON Expression?

Allow us to first perceive the CRON expression contains six elements – second, minute, hour, day, month, and day of the week in Azure Operate, and each factor is separated with the help of utilizing house. We will specify the next distinctive characters throughout the expression.

  • A comma (,) is used to specify the itemizing of values
  • A forward slash (/) is used to reoccurs execution time
  • An asterisk Time Triggered Azure Functions - A guide to background tasks using C# means that the expression may have any worth
  • A hyphen (-) suggests a quantity of values

Pattern examples of CRON Expressions

Time Triggered Azure Functions - A guide to background tasks using C#

Picture Courtesy: Working With Timer-Triggered Azure Features

Configure the CRON expression

By default when organising the venture the perform can have the 5 min set off expression within the code itself. So it’s extremely exhausting to keep up this expression in school recordsdata to keep away from these we will declare a variable within the native.settings.json file and fix the respective CRON expression and use these variables in C# code and this makes our life simple whereas sustaining a number of gadgets. On this file, as we talked about earlier that we’re going to add two expressions one is for each 5 minutes and one other one is for each 1 minute.

See the code beneath,

native.settings.json

{
    "IsEncrypted": false,
    "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet",
        //CRON Expression - 
        "EveryFiveMinutes": "0 */5 * * * *",
        "EveryMin": "0 */1 * * * *"
    }
}

Configure the Operate strategies

let’s add the AppDbContext because the Constructor Injection wherein we will devour the respective tables to carry out the Entity Framework Transactions and add the 2 features for including and fetching the info from the Database. The time set off expression is fetching from the native.settings.json file and now the 2 features have been configured and when you run the Azure perform the respective duties will carry out with their timelines.

Function1.cs

utilizing Microsoft.Azure.WebJobs;
utilizing Microsoft.Extensions.Logging;
utilizing System;
utilizing System.Linq;
utilizing TimeTrigger_AzureFunction.Fashions;

namespace TimeTrigger_AzureFunction
{
    public class Function1
    {
        #area Property
        personal readonly AppDbContext _appDbContext;
        #endregion

        #area Constructor
        public Function1(AppDbContext appDbContext)
        {
            _appDbContext = appDbContext;
        }
        #endregion
        [FunctionName("JobExecution")]
        public void InsertData([TimerTrigger("%EveryMin%")] TimerInfo myTimer, ILogger log)
        {
            var worker = new Worker { Title = "Jay", IsActive = true,AddMinutes = DateTime.Now};
            _appDbContext.Staff.AddAsync(worker);
            _appDbContext.SaveChangesAsync();
            log.LogInformation($"C# Timer set off perform executed at: {DateTime.Now}");
        }
        [FunctionName("FetchResults")]
        public void FetchData([TimerTrigger("%EveryFiveMinutes%")] TimerInfo myTimer, ILogger log)
        {
            var information = _appDbContext.Staff.ToList();
            log.LogInformation($"Whole Data Depend : {information.Depend}");
        }
    }
}

Disabling a Operate

A routine function execution could also be notably disruptive while trying to verify or debug an unrelated concern, so it is ready to moreover be helpful to disable your timer-triggered function. To disable the function, exchange native.setting.json with a model new key for AzureWebJobs.Disabled set to “true” as a default:

 //To disable a selected Funtion from executing
    "AzureWebJobs.FetchResults.Disabled": "true",

Testing the Features

Run the venture and it’ll run with a storage emulator within the background and within the command immediate we will see the outcomes of the roles.

Time Triggered Azure Functions - A guide to background tasks using C#

Abstract

On this article, we realized the right way to implement the background jobs/scheduled duties utilizing the Time-triggered Azure Features and integrating with the Database through the use of the Entity Framework Core Dependency Injection. I hope this text helps you.

Thanks for studying, please let me know your questions, ideas, or suggestions within the feedback part. I admire your suggestions and encouragement.

Continue to learn….!

Tags
Show More

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Close