.net core 定时任务
时间: 2023-06-22 20:45:49 浏览: 56
在 .NET Core 中,可以使用 Hangfire 库来实现定时任务。Hangfire 是一个开源的 .NET 库,可以用于在 .NET 和 .NET Core 应用程序中执行后台任务和定时任务。
以下是使用 Hangfire 实现定时任务的步骤:
1. 安装 Hangfire 库
在 Visual Studio 中,打开 NuGet 包管理器控制台,输入以下命令来安装 Hangfire 库:
```
Install-Package Hangfire
```
2. 配置 Hangfire
在 .NET Core 应用程序的 Startup.cs 文件中,添加以下代码来配置 Hangfire:
```csharp
public void ConfigureServices(IServiceCollection services)
{
// 添加 Hangfire 服务
services.AddHangfire(config =>
{
// 配置 Hangfire 数据库连接字符串
config.UseSqlServerConnectionString(Configuration.GetConnectionString("Hangfire"));
});
// 注册 Hangfire 服务
services.AddHangfireServer();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// 启用 Hangfire 面板
app.UseHangfireDashboard();
}
```
其中,`UseSqlServerConnectionString` 方法用于配置 Hangfire 数据库连接字符串,`AddHangfireServer` 方法用于注册 Hangfire 服务,`UseHangfireDashboard` 方法用于启用 Hangfire 面板。
3. 创建定时任务
在 .NET Core 应用程序中,可以使用 Hangfire 提供的 `RecurringJob` 类来创建定时任务。以下是一个例子:
```csharp
RecurringJob.AddOrUpdate(() => Console.WriteLine("Hello, Hangfire!"), Cron.Minutely);
```
上述代码会在每分钟执行一次 Console.WriteLine 方法。
4. 启动定时任务
在 .NET Core 应用程序中,可以使用以下代码来启动 Hangfire 定时任务:
```csharp
app.UseHangfireServer();
```
5. 运行应用程序
现在,可以运行 .NET Core 应用程序,并访问 Hangfire 面板来查看定时任务的状态和执行情况。
希望这些信息对你有所帮助,如果你需要更详细的信息,可以参考 Hangfire 官方文档。