I want to schedule a task in AWS using C#.
Previously, I did this using EventBridge rules. However, with the introduction of the new EventBridge Scheduler functionality in AWS, I'd like to re-implement it.
Here's how I currently do it:
var putRuleRequest = new PutRuleRequest
{
Name = ruleName,
ScheduleExpression = cronExpression,
State = isEnabled ? RuleState.ENABLED : RuleState.DISABLED,
Description = "Demo",
};
var putRuleResponse = eventBridgeClient.PutRule(putRuleRequest);
My goal is to invoke a Lambda from the Scheduler.
How can I create an Amazon EventBridge schedule using the AWS SDK for .NET?
To create a schedule for the Amazon EventBridge Scheduler, create a CreateScheduleRequest
and pass it to the CreateSchedule
method, part of the IAmazonScheduler
interface.
Make sure you have the the AWSSDK.Scheduler
Nuget package installed for your project. As per the API documentation, the following properties are required as a minimum:
Note that you can no longer define the targets post schedule creation (like you could with rules) & that you must define a target at the time of creation.
using Amazon.Scheduler;
using Amazon.Scheduler.Model;
var schedulerClient = new AmazonSchedulerClient();
var scheduleTimeWindow = new FlexibleTimeWindow
{
Mode = FlexibleTimeWindowMode.OFF
};
var invokeLambdaTarget = new Target
{
Arn = "arn:aws:lambda:eu-west-1:123456789012:function:HelloWorld",
RoleArn = "arn:aws:iam::123456789012:role/SchedulerExecutionRole",
Input = "{ 'Payload': 'TEST_PAYLOAD' }"
};
var createScheduleRequest = new CreateScheduleRequest
{
Name = "MyDemoSchedule",
ScheduleExpression = "cron(0 12 * * ? *)",
State = ScheduleState.ENABLED,
Description = "Demo description",
FlexibleTimeWindow = scheduleTimeWindow,
Target = invokeLambdaTarget
};
var createScheduleResponse =
await schedulerClient.CreateScheduleAsync(createScheduleRequest);