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

C#项目中程序化定时下载第三方API JSON响应文件的实现方法及技术选型疑问

解决C#项目中定时下载第三方API JSON数据的问题

嘿,刚好我之前做过类似的需求,来帮你拆解这两个问题!

一、先明确:C#和JavaScript都能完成这个任务

  • 如果你的项目是C#后端/桌面应用,直接用C#实现最方便——和你的项目技术栈统一,维护起来更顺手;
  • 如果是前端场景(比如需要在Node.js服务里执行),JavaScript也完全没问题,但如果是浏览器端JS的话,会受跨域限制,不太适合这种定时后台下载的需求,所以更推荐用Node.js或者C#来做。

二、C#实现定时下载JSON到项目文件夹的具体方案

这里分两步走:先写单次下载保存的逻辑,再加上定时触发的机制。

1. 单次下载并保存JSON的核心代码

用HttpClient请求API,再把响应内容写入项目文件夹。注意HttpClient最好用单例模式,避免频繁创建销毁连接造成资源浪费:

using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

public class JsonDownloader
{
    // 单例HttpClient,避免重复创建连接
    private static readonly HttpClient _httpClient = new HttpClient();
    private readonly string _apiUrl;
    private readonly string _saveFilePath;

    public JsonDownloader(string apiUrl)
    {
        _apiUrl = apiUrl;
        // 获取项目根目录路径,可根据实际需求调整(比如输出目录)
        _saveFilePath = Path.Combine(AppContext.BaseDirectory, "latest_data.json");
    }

    public async Task DownloadAndSaveJsonAsync()
    {
        try
        {
            // 请求API获取JSON内容
            var jsonContent = await _httpClient.GetStringAsync(_apiUrl);
            
            // 将内容写入项目文件夹下的文件
            await File.WriteAllTextAsync(_saveFilePath, jsonContent);
            Console.WriteLine($"JSON已成功保存到:{_saveFilePath}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"下载或保存失败:{ex.Message}");
            // 这里可以根据需求添加重试逻辑、日志记录等
        }
    }
}

2. 添加定时触发逻辑

用System.Timers.Timer实现每30分钟自动执行一次下载任务:

public class ScheduledDownloader
{
    private readonly Timer _timer;
    private readonly JsonDownloader _downloader;

    public ScheduledDownloader(string apiUrl)
    {
        _downloader = new JsonDownloader(apiUrl);
        // 设置定时间隔:30分钟 = 30*60*1000 = 1800000毫秒
        _timer = new Timer(1800000);
        // 绑定定时触发的事件
        _timer.Elapsed += async (sender, e) => await _downloader.DownloadAndSaveJsonAsync();
        // 设置重复触发
        _timer.AutoReset = true;
        _timer.Start();
        // 程序启动时先立即下载一次,不用等30分钟
        _downloader.DownloadAndSaveJsonAsync().Wait();
    }
}

最后在项目启动时初始化这个定时任务就行,比如控制台应用的Program.cs里:

var scheduledDownloader = new ScheduledDownloader("你的第三方API地址");
// 保持程序运行(控制台应用需要这行)
Console.ReadLine();

三、JavaScript(Node.js)实现的参考方案

如果想用JS来做,需要在Node.js环境下执行,配合node-fetch或者axios,加上setInterval:

const fetch = require('node-fetch');
const fs = require('fs').promises;
const path = require('path');

const API_URL = '你的第三方API地址';
const SAVE_PATH = path.join(__dirname, 'latest_data.json');

async function downloadAndSaveJson() {
    try {
        const response = await fetch(API_URL);
        const jsonContent = await response.text();
        await fs.writeFile(SAVE_PATH, jsonContent);
        console.log(`JSON已保存到:${SAVE_PATH}`);
    } catch (err) {
        console.error(`下载失败:${err.message}`);
    }
}

// 启动时立即下载一次
downloadAndSaveJson();
// 每30分钟执行一次下载
setInterval(downloadAndSaveJson, 30 * 60 * 1000);

一些实用提醒

  • 记得处理异常:比如API请求失败、网络中断、文件写入权限不足等情况;
  • 如果API需要身份验证(比如Token),要在请求头里添加对应的认证信息;
  • 项目文件夹路径可能因发布方式不同而变化,比如发布成单文件时,AppContext.BaseDirectory的位置会有调整,需要根据实际情况适配;
  • 定时任务的精度:Timer和setInterval都不是绝对精确的,但对于30分钟的间隔来说完全够用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 11:53:09