.net 如何在Azure Durable函数中设置备份超时

2ledvvac  于 2023-10-21  发布在  .NET
关注(0)|答案(2)|浏览(108)
[Function("TimerTrigger_EveryMinute")]
public async Task TimerTrigger_EveryMinute(
[TimerTrigger("0 * * * * *")] TimerInfo timerInfo,
[DurableClient] DurableTaskClient starter)
{
    _logger.LogError($"Running timer trigger");

    string instanceId = await starter.ScheduleNewOrchestrationInstanceAsync("ORCHESTRATOR_TRIGGER_NAME");
    await starter.WaitForInstanceCompletionAsync(instanceId);

    _logger.LogInformation($"Completed orchestration with ID = '{instanceId}'");
}

 [Function("ORCHESTRATOR_TRIGGER_NAME")]
 public async Task Run(
     [OrchestrationTrigger] TaskOrchestrationContext context)
 {
    //long running function

     await Task.WhenAll(response);
 }

**我需要的是:

1)在调用配置后,我需要在30秒时超时,所以超时后它应该结束/退出。或者2)有没有什么方法可以让这个WaitForInstanceCompletionAsync()超时。**

bbuxkriu

bbuxkriu1#

调用超时函数后,可以通过以下方式将超时设置为30秒-

[Function("ORCHESTRATOR_TRIGGER_NAME")]
public static async Task<bool> Run(
    [OrchestrationTrigger] TaskOrchestrationContext context)
{
    TimeSpan timeout = TimeSpan.FromSeconds(30);
    DateTime deadline = context.CurrentUtcDateTime.Add(timeout);

    using (var cts = new CancellationTokenSource())
    {
        Task activityTask = context.CallActivityAsync(your activity function);
        Task timeoutTask = context.CreateTimer(deadline, cts.Token);

        Task winner = await Task.WhenAny(activityTask, timeoutTask);
        if (winner == activityTask)
        {
            // success case
            cts.Cancel();
            return true;
        }
        else
        {
            // timeout case
            return false;
        }
    }

你可以参考这个文档来了解更多的细节。
您还可以通过在host.json文件中添加{ "functionTimeout": "00:00:30" }来在函数级别设置超时。

juud5qan

juud5qan2#

谢谢你的回答。如果有一个以上的ActivityTrigger,它会工作吗?我在下面提供了更多的代码。

[Function("TimerTrigger_EveryMinute")]
public async Task TimerTrigger_EveryMinute(
[TimerTrigger("0 * * * * *")] TimerInfo timerInfo,
[DurableClient] DurableTaskClient starter)
{
    _logger.LogError($"Running timer trigger");

    string instanceId = await starter.ScheduleNewOrchestrationInstanceAsync("ORCHESTRATOR_TRIGGER_NAME");
    await starter.WaitForInstanceCompletionAsync(instanceId);

    _logger.LogInformation($"Completed orchestration with ID = '{instanceId}'");
}

 [Function("ORCHESTRATOR_TRIGGER_NAME")]
 public async Task Run(
     [OrchestrationTrigger] TaskOrchestrationContext context)
 {
    var parallelTasks = new List<Task<int>>();

    for (int i = 0; i < 5; i++)
    {
        Task<int> task = context.CallActivityAsync<int>("getdata", i);
        parallelTasks.Add(task);
    }

    await Task.WhenAll(parallelTasks);
 }

相关问题