Hay más AWS SDK ejemplos disponibles en el GitHub repositorio de AWS Doc SDK Examples
Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.
Úselo CreateSchedule
con un AWS SDK
En los siguientes ejemplos de código se muestra cómo se utiliza CreateSchedule
.
Los ejemplos de acciones son extractos de código de programas más grandes y deben ejecutarse en contexto. Puede ver esta acción en contexto en el siguiente ejemplo de código:
- .NET
-
- AWS SDK for .NET
-
nota
Hay más en marcha GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. /// <summary> /// Creates a new schedule in Amazon EventBridge Scheduler. /// </summary> /// <param name="name">The name of the schedule.</param> /// <param name="scheduleExpression">The schedule expression that defines when the schedule should run.</param> /// <param name="scheduleGroupName">The name of the schedule group to which the schedule should be added.</param> /// <param name="deleteAfterCompletion">Indicates whether to delete the schedule after completion.</param> /// <param name="useFlexibleTimeWindow">Indicates whether to use a flexible time window for the schedule.</param> /// <param name="targetArn">ARN of the event target.</param> /// <param name="roleArn">Execution Role ARN.</param> /// <returns>True if the schedule was created successfully, false otherwise.</returns> public async Task<bool> CreateScheduleAsync( string name, string scheduleExpression, string scheduleGroupName, string targetArn, string roleArn, string input, bool deleteAfterCompletion = false, bool useFlexibleTimeWindow = false) { try { int hoursToRun = 1; int flexibleTimeWindowMinutes = 10; var request = new CreateScheduleRequest { Name = name, ScheduleExpression = scheduleExpression, GroupName = scheduleGroupName, Target = new Target { Arn = targetArn, RoleArn = roleArn, Input = input }, ActionAfterCompletion = deleteAfterCompletion ? ActionAfterCompletion.DELETE : ActionAfterCompletion.NONE, StartDate = DateTime.UtcNow, // Ignored for one-time schedules. EndDate = DateTime.UtcNow .AddHours(hoursToRun) // Ignored for one-time schedules. }; // Allow a flexible time window if the caller specifies it. request.FlexibleTimeWindow = new FlexibleTimeWindow { Mode = useFlexibleTimeWindow ? FlexibleTimeWindowMode.FLEXIBLE : FlexibleTimeWindowMode.OFF, MaximumWindowInMinutes = useFlexibleTimeWindow ? flexibleTimeWindowMinutes : null }; var response = await _amazonScheduler.CreateScheduleAsync(request); Console.WriteLine($"Successfully created schedule '{name}' " + $"in schedule group '{scheduleGroupName}': {response.ScheduleArn}."); return true; } catch (ConflictException ex) { // If the name is not unique, a ConflictException will be thrown. _logger.LogError($"Failed to create schedule '{name}' due to a conflict. {ex.Message}"); return false; } catch (Exception ex) { _logger.LogError($"An error occurred while creating schedule '{name}' " + $"in schedule group '{scheduleGroupName}': {ex.Message}"); return false; } }
-
Para API obtener más información, consulte CreateSchedulela AWS SDK for .NET APIReferencia.
-
- Java
-
- SDKpara Java 2.x
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. /** * Creates a new schedule for a target task. * * @param name the name of the schedule * @param scheduleExpression The schedule expression that defines when the schedule should run. * @param scheduleGroupName the name of the schedule group to which the schedule belongs * @param targetArn the Amazon Resource Name (ARN) of the target task * @param roleArn the ARN of the IAM role to be used for the schedule * @param input the input data for the target task * @param deleteAfterCompletion whether to delete the schedule after it's executed * @param useFlexibleTimeWindow whether to use a flexible time window for the schedule execution * @return true if the schedule was successfully created, false otherwise */ public CompletableFuture<Boolean> createScheduleAsync( String name, String scheduleExpression, String scheduleGroupName, String targetArn, String roleArn, String input, boolean deleteAfterCompletion, boolean useFlexibleTimeWindow) { int hoursToRun = 1; int flexibleTimeWindowMinutes = 10; Target target = Target.builder() .arn(targetArn) .roleArn(roleArn) .input(input) .build(); FlexibleTimeWindow flexibleTimeWindow = FlexibleTimeWindow.builder() .mode(useFlexibleTimeWindow ? FlexibleTimeWindowMode.FLEXIBLE : FlexibleTimeWindowMode.OFF) .maximumWindowInMinutes(useFlexibleTimeWindow ? flexibleTimeWindowMinutes : null) .build(); Instant startDate = Instant.now(); Instant endDate = startDate.plus(Duration.ofHours(hoursToRun)); CreateScheduleRequest request = CreateScheduleRequest.builder() .name(name) .scheduleExpression(scheduleExpression) .groupName(scheduleGroupName) .target(target) .actionAfterCompletion(deleteAfterCompletion ? ActionAfterCompletion.DELETE : ActionAfterCompletion.NONE) .startDate(startDate) .endDate(endDate) .flexibleTimeWindow(flexibleTimeWindow) .build(); return getAsyncClient().createSchedule(request) .thenApply(response -> { logger.info("Successfully created schedule {} in schedule group {}, The ARN is {} ", name, scheduleGroupName, response.scheduleArn()); return true; }) .whenComplete((result, ex) -> { if (ex != null) { if (ex instanceof ConflictException) { // Handle ConflictException logger.error("A conflict exception occurred while creating the schedule: {}", ex.getMessage()); throw new CompletionException("A conflict exception occurred while creating the schedule: " + ex.getMessage(), ex); } else { throw new CompletionException("Error creating schedule: " + ex.getMessage(), ex); } } }); }
-
Para API obtener más información, consulte CreateSchedulela AWS SDK for Java 2.x APIReferencia.
-
- Python
-
- SDKpara Python (Boto3)
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. class SchedulerWrapper: def __init__(self, eventbridge_scheduler_client: client): self.scheduler_client = eventbridge_scheduler_client @classmethod def from_client(cls) -> "SchedulerWrapper": """ Creates a SchedulerWrapper instance with a default EventBridge Scheduler client. :return: An instance of SchedulerWrapper initialized with the default EventBridge Scheduler client. """ eventbridge_scheduler_client = boto3.client("scheduler") return cls(eventbridge_scheduler_client) def create_schedule( self, name: str, schedule_expression: str, schedule_group_name: str, target_arn: str, role_arn: str, input: str, delete_after_completion: bool = False, use_flexible_time_window: bool = False, ) -> str: """ Creates a new schedule with the specified parameters. :param name: The name of the schedule. :param schedule_expression: The expression that defines when the schedule runs. :param schedule_group_name: The name of the schedule group. :param target_arn: The Amazon Resource Name (ARN) of the target. :param role_arn: The Amazon Resource Name (ARN) of the execution IAM role. :param input: The input for the target. :param delete_after_completion: Whether to delete the schedule after it completes. :param use_flexible_time_window: Whether to use a flexible time window. :return The ARN of the created schedule. """ try: hours_to_run = 1 flexible_time_window_minutes = 10 parameters = { "Name": name, "ScheduleExpression": schedule_expression, "GroupName": schedule_group_name, "Target": {"Arn": target_arn, "RoleArn": role_arn, "Input": input}, "StartDate": datetime.now(timezone.utc), "EndDate": datetime.now(timezone.utc) + timedelta(hours=hours_to_run), } if delete_after_completion: parameters["ActionAfterCompletion"] = "DELETE" if use_flexible_time_window: parameters["FlexibleTimeWindow"] = { "Mode": "FLEXIBLE", "MaximumWindowInMinutes": flexible_time_window_minutes, } else: parameters["FlexibleTimeWindow"] = {"Mode": "OFF"} response = self.scheduler_client.create_schedule(**parameters) return response["ScheduleArn"] except ClientError as err: if err.response["Error"]["Code"] == "ConflictException": logger.error( "Failed to create schedule '%s' due to a conflict. %s", name, err.response["Error"]["Message"], ) else: logger.error( "Error creating schedule: %s", err.response["Error"]["Message"] ) raise
-
Para API obtener más información, consulte CreateSchedulela AWS SDKreferencia de Python (Boto3). API
-