zhengzhou-byd-lms/DOAN.Service/BackService/MyBackgroundService.cs

53 lines
1.8 KiB
C#
Raw Normal View History

2025-03-05 08:59:58 +08:00
using Microsoft.Extensions.Hosting;
using System.Diagnostics.Metrics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
public class MyBackgroundService : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
//具体的后台任务逻辑
var url = "/api/product/Product_Information?Product006_ProductParameters"; // 替换成你的URL
var data = new { serviceId = "John Doe", Age = 30 }; // 创建要发送的数据对象
var jsonData = JsonConvert.SerializeObject(data);
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
var request = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = content
};
// 添加请求头
request.Headers.Add("appId", "61320D6EEF5A48B7C32149DF991BED41");
request.Headers.Add("appKey", "85725BB0BCCEE8DB1AE2D5A48D393ABE");
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
try
{
await Task.Delay(TimeSpan.FromMinutes(10), stoppingToken); // 每隔10分钟执行一次
}
catch (TaskCanceledException)
{
// 当CancellationToken被触发时Task.Delay会抛出TaskCanceledException。
// 这里可以什么都不做或者记录日志等,然后退出循环。
break;
}
}
}
}