LoginSignup
0
1

More than 3 years have passed since last update.

[Azure Functions] 長めの処理時間をかける関数 (C#)

Last updated at Posted at 2020-11-26

はじめに

Azure Functions では、SKU によって処理上限時間が決まっています (参考)。
これを試験とかで試してみる用に関数を作成したので、とりあえず公開しておこうかなと思います。

環境

  • .NET Core 3.1

コード

Visual Studio 2019 のテンプレートから HTTP Trigger で作成し、ちょちょっと変えただけですが。

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace LongRunFunctions01
{
    public static class Function1
    {
        [FunctionName("LongRunFunction01")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            // デフォルトでは5秒実行
            int sec = 5;

            // sec というパラメータに入れた数字を秒数として、その時間だけ実行する
            if (req.Query.ContainsKey("sec"))
            {
                sec = int.Parse(req.Query["sec"]);
            }

            for (int i = 0; i < sec; i++)
            {
                await Task.Delay(1000);
                if(i % 10 == 0)
                {
                    log.LogInformation($"{i} sec");
                }
            }

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);

            string responseMessage = "This HTTP triggered function executed successfully. ";

            return new OkObjectResult(responseMessage);
        }
    }
}

Usage

下記のようにアクセスすると、100秒間実行しようとします。

<URL>/LongRunFunction01?sec=100

さいごに

インフラエンジニアにとっては、こういうインフラの動きを試すためにコードを書く必要が出てきたりしていますね。良い勉強になるので、今後も色々と試してみようと思います。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1