You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

需求:创建Azure Timer Function每10分钟定时调用指定WebAPI

Alright, let's get this Azure Timer Function set up to call your Web API every 10 minutes—no console app required. Here's a step-by-step breakdown tailored to get you up and running smoothly:

Step 1: Create an Azure Timer Function Resource

First, you'll need to spin up a Timer Function in Azure:

  • Head to the Azure Portal, search for Function App, and create a new one (pick your preferred runtime—C#, Python, etc.).
  • Once the Function App is ready, go to it, click Functions > Create, select the Timer trigger template, and give your function a name.
Step 2: Configure the 10-Minute Schedule

Azure uses a 6-field CRON expression for timer triggers (format: second minute hour day month weekday). For a 10-minute interval, use this schedule:

0 */10 * * * *
  • Breakdown: 0 (run at the start of the minute), */10 (every 10 minutes), followed by wildcards for any hour, day, month, or weekday.
  • Paste this into the Schedule field when creating the timer trigger, or edit it later in the function's function.json (for Python) or the attribute (for C#).
Step 3: Write the Code to Call Your Web API

Below are examples for two popular runtimes—pick the one that matches your setup:

C# Example

We'll reuse a single HttpClient instance to avoid socket exhaustion (a critical best practice):

using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;

public static class APICallTimerFunction
{
    // Reuse HttpClient across function invocations
    private static readonly HttpClient _httpClient = new HttpClient();

    [FunctionName("CallWebApiEvery10Minutes")]
    public static async Task Run([TimerTrigger("0 */10 * * * *")] TimerInfo myTimer, ILogger log)
    {
        log.LogInformation($"Timer trigger fired at: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");

        try
        {
            // Replace with your actual Web API endpoint
            var apiEndpoint = "https://your-api-domain.com/target-endpoint";
            
            var response = await _httpClient.GetAsync(apiEndpoint);
            response.EnsureSuccessStatusCode(); // Throws if HTTP status is 4xx/5xx

            var responseContent = await response.Content.ReadAsStringAsync();
            log.LogInformation($"API call succeeded. Response snippet: {responseContent.Substring(0, 100)}...");
        }
        catch (Exception ex)
        {
            log.LogError(ex, "Failed to call the Web API—check URL, authentication, or API availability");
        }
    }
}

Python Example

We'll use a reusable requests.Session for better performance:

import azure.functions as func
import requests
import logging
import datetime

# Reuse session to persist connections
api_session = requests.Session()

def main(mytimer: func.TimerRequest) -> None:
    utc_now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
    
    if mytimer.past_due:
        logging.warning("Timer is running late—check function execution time!")

    logging.info(f"Timer trigger executed at: {utc_now}")

    try:
        # Replace with your actual Web API endpoint
        api_endpoint = "https://your-api-domain.com/target-endpoint"
        
        response = api_session.get(api_endpoint)
        response.raise_for_status() # Raises exception for HTTP errors

        logging.info(f"API call succeeded. Response snippet: {response.text[:100]}...")
    except Exception as ex:
        logging.error(f"API call failed: {str(ex)}")
Step 4: Test & Deploy
  • Local Testing: Use Azure Functions Core Tools to run the function locally first—this lets you verify the API call works without deploying to Azure.
  • Deploy: If you wrote the code locally (e.g., in VS Code), use the Azure extension to deploy directly to your Function App. If using the portal, paste the code into the inline code editor.
Key Notes to Avoid Issues
  • Authentication: If your Web API requires auth (API key, OAuth token), add the necessary headers to the client/session. For example, in C#:
    _httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer YOUR_ACCESS_TOKEN");
    
  • Logging: The examples include detailed logging to help you debug failed calls—check the Function App's Logs tab in the portal for real-time feedback.
  • Function Execution Time: Ensure your API call completes within Azure's function timeout limits (default is 5 minutes, which is more than enough for most API calls).

内容的提问来源于stack exchange,提问作者Chirag Patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:17:11