AWS步骤函数的持续时间是根据步骤函数中每个步骤的执行时间累加而来的。每个步骤的执行时间取决于该步骤中运行的任务或Lambda函数的执行时间。
以下是一个使用AWS步骤函数计算持续时间的示例代码:
import time
def lambda_handler(event, context):
# 模拟一个耗时的任务,睡眠5秒钟
time.sleep(5)
return {
'statusCode': 200,
'body': 'Task completed successfully!'
}
{
"Comment": "A simple AWS Step Functions state machine that executes a long running task",
"StartAt": "LongRunningTask",
"States": {
"LongRunningTask": {
"Type": "Task",
"Resource": "arn:aws:lambda:REGION:ACCOUNT_ID:function:longRunningTask",
"End": true
}
}
}
请确保将 "REGION" 替换为您的AWS区域,"ACCOUNT_ID" 替换为您的AWS账户ID,并将 "longRunningTask" 替换为您创建的Lambda函数的名称。
import boto3
def start_step_function(state_machine_definition_file):
step_functions = boto3.client('stepfunctions')
with open(state_machine_definition_file, 'r') as file:
state_machine_definition = file.read()
response = step_functions.create_state_machine(
name='LongRunningTaskStateMachine',
definition=state_machine_definition,
roleArn='arn:aws:iam::ACCOUNT_ID:role/StepFunctionRole'
)
state_machine_arn = response['stateMachineArn']
response = step_functions.start_execution(
stateMachineArn=state_machine_arn
)
execution_arn = response['executionArn']
return execution_arn
请确保将 "ACCOUNT_ID" 替换为您的AWS账户ID,并将 "StepFunctionRole" 替换为具有适当权限的IAM角色的名称。
def get_execution_duration(execution_arn):
step_functions = boto3.client('stepfunctions')
response = step_functions.describe_execution(
executionArn=execution_arn
)
start_time = response['startDate']
stop_time = response['stopDate']
duration = stop_time - start_time
return duration.total_seconds()
state_machine_definition_file = 'state_machine_definition.json'
execution_arn = start_step_function(state_machine_definition_file)
execution_duration = get_execution_duration(execution_arn)
print(f'Step function execution duration: {execution_duration} seconds')
通过运行上述代码,您将能够启动步骤函数并获取其执行的持续时间(以秒为单位)。