Azure WebJobs SDK

repository·dev·Indexed 20 days ago

https://github.com/azure/azure-webjobs-sdk

A framework for building background processing applications in Azure using a declarative trigger and binding model. It supports built-in services like Azure Storage Blobs, Queues, Tables, and Service Bus, and is extensible via custom triggers and bindings. The SDK can be hosted in Azure WebJobs (part of Azure Web Apps) or Azure Worker Roles. Key components include Microsoft.Azure.WebJobs.Core for definitions, Microsoft.Azure.WebJobs.Host for runtime management, and RPC capabilities via Microsoft.Azure.WebJobs.Rpc.Core.

Tokens
2.7K
Snippets
6
Records
16
Agent score
73%

What's inside Azure WebJobs SDK

  1. Overview of Azure WebJobs SDK

    dev

    The Azure WebJobs SDK is a framework designed to simplify writing background processing code for Azure. It provides a declarative system for handling data through two primary mechanisms:

    • Triggers: Automatically invokes your code when new data is received (e.g., in a queue or blob).
    • Bindings: Simplifies reading from or writing to Azure services.

    Supported Built-in Services:

    • Azure Storage Blobs
    • Azure Storage Queues
    • Azure Storage Tables
    • Azure Service Bus

    Extensibility: The SDK is fully extensible. You can plug in new trigger and binding types. Common extensions include:

    • File trigger/binder
    • Timer/Cron trigger
    • WebHook HTTP trigger
    • SendGrid email binding
  2. How to host and run Azure WebJobs SDK

    dev

    You can host the Azure WebJobs SDK in several environments:

    1. Azure WebJobs (Recommended): Part of Azure Web Apps. This allows you to run background tasks or services within a Web App. You can upload executables (such as .exe, .cmd, or .bat files) to run. Using the SDK with Azure WebJobs provides an integrated Dashboard in the Azure portal for monitoring and diagnostics.
    2. Azure Worker Roles: You can also run your jobs within a Worker Role.
  3. Configure Application Insights logging for WebJobs

    dev

    To enable Application Insights logging in your WebJobs SDK host, use the AddApplicationInsightsWebJobs extension method within the ConfigureLogging callback of your host builder. This method allows you to configure ApplicationInsightsLoggerOptions, such as setting the InstrumentationKey.

    Commonly used types in this package include:

    • ApplicationInsightsLoggingBuilderExtensions: Provides the extension methods for configuration.
    • ApplicationInsightsLoggerProvider: The provider responsible for routing logs to Application Insights.
    • ApplicationInsightsLoggerOptions: Configuration options for the logger.
    using System.Threading.Tasks;
    using Microsoft.Extensions.Hosting;
    using Microsoft.Extensions.Logging;
    
    class Program
    {
        public static async Task Main(string[] args)
        {
            var builder = Host.CreateDefaultBuilder(args)
                .ConfigureWebJobs(b =>
                {
                    b.AddAzureStorageCoreServices();
                    b.AddAzureStorageQueues();
                })
                .ConfigureLogging((context, b) =>
                {
                    // If this key exists in any config, use it to enable App Insights
                    string appInsightsKey = context.Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"];
                    if (!string.IsNullOrEmpty(appInsightsKey))
                    {
                        b.AddApplicationInsightsWebJobs(o => o.InstrumentationKey = appInsightsKey);
                    }
                });
    
            using var host = builder.Build();
            await host.RunAsync();
        }
    }
  4. Register Azure Storage services in WebJobs

    dev

    To enable Azure Storage-based implementations of WebJobs SDK component interfaces, use the extension methods provided by this package on the IWebJobsBuilder.

    Commonly used registration methods include:

    • AddAzureStorageCoreServices(): Registers the core Azure Storage services required by the WebJobs SDK.
    • AddAzureStorageQueues(): Registers Azure Storage Queue support.
    using System.Threading.Tasks;
    using Microsoft.Extensions.Hosting;
    
    class Program
    {
        public static async Task Main(string[] args)
        {
            var builder = Host.CreateDefaultBuilder(args)
                .ConfigureWebJobs(b =>
                {
                    b.AddAzureStorageCoreServices();
                    b.AddAzureStorageQueues();
                });
    
            using var host = builder.Build();
            await host.RunAsync();
        }
    }
  5. Configure and start a JobHost in a console application

    dev

    To run a WebJobs host within a .NET console application, use the Microsoft.Extensions.Hosting integration. You can use Host.CreateDefaultBuilder(args) and call .ConfigureWebJobs() to register necessary WebJobs services. Inside the ConfigureWebJobs delegate, you can add specific storage or service extensions like AddAzureStorageCoreServices() and AddAzureStorageQueues(). Once configured, build the host and call RunAsync() to start the job execution lifecycle.

    using System.Threading.Tasks;
    using Microsoft.Extensions.Hosting;
    
    class Program
    {
        public static async Task Main(string[] args)
        {
            var builder = Host.CreateDefaultBuilder(args)
                .ConfigureWebJobs(b =>
                {
                    b.AddAzureStorageCoreServices();
                    b.AddAzureStorageQueues();
                });
    
            using var host = builder.Build();
            await host.RunAsync();
        }
    }
  6. Register a custom gRPC extension in WebJobs

    dev

    You can extend the WebJobs SDK with custom gRPC services by using the MapWorkerGrpcService<T> method provided by WebJobsExtensionBuilderRpcExtensions. This allows communication between the host and the worker via RPC.

    To implement this, you typically:

    1. Use builder.AddExtension<TConfigProvider>() to register your extension's configuration.
    2. Call .MapWorkerGrpcService<TService>() to map the gRPC service to the worker.
    3. Register the service implementation itself in the dependency injection container (e.g., using builder.Services.AddSingleton<TService>()).
    public static IWebJobsBuilder AddMyExtension(this IWebJobsBuilder builder, Action<MyExtensionOptions> configure)
    {
        builder.AddExtension<MyExtensionConfigProvider>()
            .MapWorkerGrpcService<MyGrpcService>();
    
        builder.Services.AddSingleton<MyGrpcService>();
    
        return builder;
    }
  7. Create a QueueTrigger function with a timeout

    dev

    To create a function that processes items from a queue, use the [QueueTrigger] attribute on a parameter. You can combine this with [Timeout] to manage long-running tasks. Ensure you include the Microsoft.Azure.WebJobs namespace.

    using Microsoft.Azure.WebJobs;
    
    [TimeoutAttribute("00:15:00")]
    public void ProcessWorkItem([QueueTrigger("test")] WorkItem workItem, ILogger logger)
    {
        logger.LogInformation($"Processed work item {workItem.ID}");
    }