A common use case when working with AWS Lambda and .NET is running code on a schedule, similar to a cron job. AWS makes this easy with Amazon CloudWatch Events (now part of Amazon EventBridge), allowing you to repeatedly trigger Lambda functions. In this post, we’ll walk through how to schedule a .NET Lambda function using CloudWatch and how to structure your code for maintainability.
Prerequisites Before You
Begin, Make Sure You Have The Following: An AWS Account with permission to create Lambda functions and CloudWatch rules The .NET SDK is installed (preferably .NET 6 or later)
The AWS CLI is installed and configured (aws configure)
Amazon.Lambda.Tools installed via the .NET CLI: dotnet tool install -g Amazon.Lambda.Tools Basic familiarity with AWS Lambda and the .NET CLI Step 1: Create the .NET Lambda Function You can use the AWS-provided templates with the Amazon.Lambda.Templates package. dotnet new lambda.EmptyFunction --name ScheduledTaskLambda cd ScheduledTaskLambda Edit The Function.cs File: public class Function { public async Task FunctionHandler(ILambdaContext context) { context.Logger.LogLine("Scheduled task triggered at: " + DateTime.UtcNow); // Your logic here await DoScheduledWork(); } private Task DoScheduledWork() { // Simulate a task like cleanup, email reminder, or sync Console.WriteLine("Running scheduled task..."); return Task.CompletedTask; } } Step 2: Deploy the Lambda Function Deploy The Lambda: dotnet lambda deploy-function ScheduledTaskLambda You’ll be prompted for AWS credentials and region during the deployment. Step 3: Schedule with CloudWatch Event Rule You can use the AWS Console or the AWS CLI: aws events put-rule --schedule-expression "rate(5 minutes)" --name MyScheduledLambdaRule Add The Lambda Target: aws events put-targets --rule MyScheduledLambdaRule --targets "Id"="1","Arn"="arn:aws:lambda:::function:ScheduledTaskLambda" Grant CloudWatch Permission To Invoke The Lambda:
aws lambda add-permission --function-name ScheduledTaskLambda --statement-id MyScheduledEventPermission --action 'lambda:InvokeFunction' --principal events.amazonaws.com --source-arn arn:aws:events:::rule/MyScheduledLambdaRule Using Cron Expressions Instead Of Rate()You Can Use Cron Expressions: schedule-expression "cron(0 12 ? )" This triggers at 12:00 PM UTC every day.
AWS cron format: cron(Minutes Hours Day-of-month Month Day-of-week Year) Real-World Example: Sending a Daily Email Report Let’s Say Your System Collects Usage Metrics Or User Activity Throughout The Day.
Every Morning
At 8 AM UTC, You Want To Email a Summary Report To Your Team. You’ll: Query a database or analytics source
Generate a report, either plain text or HTML
Send the report using Amazon SES or another email provider This is a great use case for a scheduled Lambda function.
Example
Code public class Function { public async Task FunctionHandler(ILambdaContext context) { var report = await GenerateReport(); await SendEmail(report); context.Logger.LogLine("Daily report sent at: " + DateTime.UtcNow); } private Task GenerateReport() { // Query a DB or metrics API.
Simulated output: return Task.FromResult("User signups: 42 Errors: 3 Sales: $1280"); } private Task SendEmail(string report) { // Integrate with Amazon SES, SendGrid, or another provider Console.WriteLine("Sending email with report: " + report); return Task.CompletedTask; } } This Lambda can be scheduled using the following cron expression: bashCopy code--schedule-expression "cron(0 8 ? )" This means 8:00 AM UTC every day. Logging and Monitoring View logs in CloudWatch Logs
Add custom logging using context.Logger.LogLine(...)
Use structured logging libraries like Serilog for better insights Summary With just a few commands and a bit of .NET code, you can schedule tasks using CloudWatch Events and AWS Lambda. This approach is scalable, cost-effective, and fully serverless.
Benefits Recap: No server maintenance
Pay only for executions
Integrated with the AWS ecosystem
Adecuado for recurring jobs like cleanup, reporting, data sync, and reminders References AWS Lambda Developer Guide (.NET)
Schedule expressions for rules - EventBridge
Amazon.Lambda.Tools GitHub
AWS Schedule Expressions
📌 Scheduling Tasks with CloudWatch and .NET Lambda (Jun)
🏢 Renato Gonçalves
📍 Jun
Postulate a este anuncio
Muestra tus habilidades a la empresa, rellenar el formulario y deja un toque personal en la carta, ayudará el reclutador en la elección del candidato.