c# - 如何在 API 中自动调用函数?
问题描述
大家好
我使用 Asp.Net Core 编写了一个 API。我希望一个函数每 10 分钟自动运行一次。我怎么能做这样的事情?
我需要你的帮助 。提前致谢。
public void AutoUpdate()
{
var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromMinutes(10);
var dbData = _provinceDataDal.GetAll();
var timer = new System.Threading.Timer((e) =>
{
UpdateData(dbData);
}, null, startTimeSpan, periodTimeSpan);
}
我使用了类似 use 的方法,但它没有按我的意愿工作。因为它只工作一次。
我希望它在上面运行我的 updateData 函数 10 分钟,而不必在 API 首次运行和再次运行时触发它。
解决方案
由于 asp.net core 2.1 是托管服务的后台任务。
一、在Startup中配置服务
public IServiceProvider ConfigureServices(IServiceCollection services)
{
//Other DI registrations;
// Register Hosted Services
services.AddHostedService<MyServices>();
}
之后,使用您想要执行的代码实现 ExecuteAsync 方法
public class MyServices : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogDebug("Starting");
stoppingToken.Register(() =>
_logger.LogDebug("Stopping."));
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogDebug($"Working");
// Your code here
await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
}
_logger.LogDebug($"Stopping.");
}
}
此链接的 Microsoft中的更多文档
推荐阅读
- ios - 权限被拒绝后可以访问照片库和相机
- java - 应用程序崩溃后服务无法继续运行
- c++ - 有没有办法从地图中获取特定的键值对?
- arrays - Kotlin 中具有“n”元素的数组不起作用
- python - 格式化由字典制作的 csv 行
- c++ - 当我使用快速排序对双向链表进行排序时,用户消失了
- c++ - 我什么时候需要使用/拥有一个makefile?
- android - Android,对于 JNI,是否应该在 InputMethodService 中调用 System.loadLibrary?
- php - bash 将输出重定向到文件 - 无法存储临时文本
- spring - Spring Boot 应用程序在 AutoConfigurationImportFilter 上失败,无法构建但未指定类