.NET CORE 定时任务
时间: 2023-10-02 16:08:57 浏览: 50
对于在.NET Core中实现定时任务,有几种不同的方法可供选择:
1. 使用System.Threading.Timer:可以使用`System.Threading.Timer`类创建一个定时器,指定要定期执行的方法以及执行间隔。例如:
```csharp
using System;
using System.Threading;
public class Program
{
public static void Main()
{
Timer timer = new Timer(DoSomething, null, TimeSpan.Zero, TimeSpan.FromSeconds(10));
// 阻止主线程退出
Console.ReadKey();
}
private static void DoSomething(object state)
{
// 执行定时任务的逻辑
Console.WriteLine("定时任务执行了!");
}
}
```
上述代码中,`DoSomething`方法将每隔10秒被执行一次。
2. 使用Hangfire:Hangfire是一个.NET的开源库,提供了一个简单的方式来执行后台作业,包括定时任务。首先,你需要在项目中安装Hangfire。然后,在Startup类的ConfigureServices方法中配置Hangfire服务:
```csharp
using Hangfire;
using Hangfire.SqlServer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
public class Startup
{
private readonly IConfiguration _configuration;
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
// 添加Hangfire服务
services.AddHangfire(configuration => configuration.UseSqlServerStorage(_configuration.GetConnectionString("HangfireConnection")));
// ...
}
public void Configure(IApplicationBuilder app)
{
// ...
// 启用Hangfire仪表板
app.UseHangfireDashboard();
// 启用Hangfire后台处理
app.UseHangfireServer();
// ...
}
}
```
然后,在任何需要执行定时任务的地方,你可以使用Hangfire的`RecurringJob`类来定义定时任务:
```csharp
using Hangfire;
public class MyJob
{
[AutomaticRetry(Attempts = 3)] // 可选:定义任务失败重试的次数
public static void DoSomething()
{
// 执行定时任务的逻辑
Console.WriteLine("定时任务执行了!");
}
}
public class Program
{
public static void Main()
{
// 使用Hangfire调度定时任务
RecurringJob.AddOrUpdate<MyJob>("MyJob", x => x.DoSomething(), Cron.Minutely);
// 阻止主线程退出
Console.ReadKey();
}
}
```
上述代码中,`DoSomething`方法将按照每分钟一次的频率被调度执行。
这些只是.NET Core中实现定时任务的一些常见方法,你可以根据自己的需求选择合适的方式来实现。