Azure WebJobs is a powerful feature of Azure App Service that allows you to run background tasks and processes in the same context as your web application. WebJobs can be used to perform tasks such as data processing, file maintenance, or any other background work that needs to be executed independently of the main web application. In this article, we'll explore what Azure WebJobs are, how they work, and provide code snippets in both Python and C#. We'll also discuss the important point that WebJobs can only be used with a Windows App Service.
What are Azure WebJobs?
Azure WebJobs are part of the Azure App Service platform, which allows you to run scripts or programs as background tasks. These tasks can be triggered on a schedule, run continuously, or triggered manually. WebJobs are particularly useful for offloading tasks that don't need to be handled synchronously within the main web application, such as sending emails, processing data, or performing maintenance tasks.
Key Features of Azure WebJobs
- Integration with Azure App Service: WebJobs run in the same context as your Azure App Service, making it easy to share resources and configurations.
- Multiple Trigger Types: WebJobs can be triggered by a schedule, a queue message, a blob, or manually.
- Scalability: WebJobs can scale with your App Service plan, allowing you to handle increased workloads.
- Monitoring and Logging: Azure provides built-in monitoring and logging for WebJobs, making it easy to track their performance and troubleshoot issues.
WebJobs and Windows App Service
An important point to note is that Azure WebJobs can only be used with a Windows App Service. This is because WebJobs relies on the Windows-based infrastructure of Azure App Service to execute tasks. If you are using a Linux-based App Service, you will need to use alternative solutions such as Azure Functions or custom Docker containers to achieve similar functionality.
Creating and Deploying Azure WebJobs
1. Creating a WebJob in C#
Let's start by creating a simple WebJob in C# that writes a message to the console.
Step 1. Create a Console Application
Create a new Console Application in Visual Studio or your preferred IDE.
Step 2. Write the Code
using System;
namespace MyWebJob
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello from Azure WebJob!");
}
}
}
Step 3. Publish the WebJob
- Right-click on the project in Visual Studio and select Publish.
- Choose Azure as the target and select Azure App Service (Windows).
- Follow the prompts to publish your WebJob to the Azure App Service.
2. Creating a WebJob in Python
Now, let's create a simple WebJob in Python that performs a similar task.
Step 1. Create a Python Script
Create a new Python script named run.py.
Step 2. Write the Code
import datetime
def main():
print(f"Hello from Azure WebJob at {datetime.datetime.now()}!")
if __name__ == "__main__":
main()
Step 3. Deploy the WebJob
- Zip the run.py file into a .zip archive.
- Go to the Azure portal, navigate to your App Service, and select WebJobs.
- Click Add and upload the .zip file.
- Configure the WebJob to run on a schedule or trigger it manually.
Triggering WebJobs
WebJobs can be triggered in several ways:
- Manual Trigger: You can manually trigger a WebJob from the Azure portal.
- Scheduled Trigger: You can configure a WebJob to run on a schedule using a CRON expression.
- Triggered by Azure Storage: WebJobs can be triggered by changes in Azure Storage, such as new messages in a queue or new blobs in a container.
Example. Triggering a WebJob with a Queue Message (C#)
Here’s an example of how to trigger a WebJob when a new message is added to an Azure Storage Queue.
C# Code
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
public static class QueueTriggerWebJob
{
[FunctionName("QueueTriggerWebJob")]
public static void Run(
[QueueTrigger("myqueue-items", Connection = "AzureWebJobsStorage")] string myQueueItem,
ILogger log)
{
log.LogInformation($"C# WebJob processed: {myQueueItem}");
}
}
Example. Triggering a WebJob with a Queue Message (Python)
Python Code
import os
from azure.storage.queue import QueueServiceClient
def main():
connection_string = os.getenv("AzureWebJobsStorage")
queue_name = "myqueue-items"
queue_service = QueueServiceClient.from_connection_string(connection_string)
queue_client = queue_service.get_queue_client(queue_name)
messages = queue_client.receive_messages()
for message in messages:
print(f"Python WebJob processed: {message.content}")
queue_client.delete_message(message)
if __name__ == "__main__":
main()
Conclusion
Azure WebJobs are a powerful tool for running background tasks in the context of an Azure App Service. They are particularly useful for offloading tasks that don't need to be handled synchronously within the main web application. However, it's important to remember that WebJobs can only be used with a Windows App Service. If you're using a Linux-based App Service, you'll need to explore alternative solutions like Azure Functions or custom Docker containers.
Whether you're using C# or Python, Azure WebJobs provide a flexible and scalable way to handle background tasks, making them an essential part of any Azure developer's toolkit.