.net core 3.x 定时任务,用的sqlite数据库,自己折腾了几天,分享出来吧,自己下次用的时候找也方便。
1、依赖包:
- hangfire (1.7.7)
- hangfire.core(1.7.7)
- hangfire.Sqlite (1.4.2)
- Microsoft.EntityFrameworkCore.Sqlite(3.1.0)
2、Startup类配置
1、实现IDashboardAuthorizationFilter ,自己根据情况实现或百度
2、ConfigureServices(IServiceCollection services) 配置参考:
var sqliteOptions = new SQLiteStorageOptions();
SQLitePCL.Batteries.Init();
services.AddHangfire(configuration => configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimpleAssemblyNameTypeSerializer().UseRecommendedSerializerSettings()
.UseLogProvider(new ColouredConsoleLogProvider())
.UseSQLiteStorage("Data Source=./wg.db;", sqliteOptions)
);
在项目根目录增加wg.db ,记得;号一定要写
3、 Configure(IApplicationBuilder app, IWebHostEnvironment env) 配置参考:
var option = new BackgroundJobServerOptions { WorkerCount = 1 };
app.UseHangfireServer(option);
app.UseDeveloperExceptionPage();
app.UseHangfireDashboard(options: new DashboardOptions { Authorization = new[] { new ClipsAuthorizeFilter() } })
.UseCors(builder => builder.AllowAnyHeader());
GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute { Attempts = 0 });
HangfireJobScheduler.ScheduleRecurringJobs();
4、HangfireJobScheduler类,定时规则代码参考:
RecurringJob.RemoveIfExists(nameof(ClipsJob));
RecurringJob.AddOrUpdate<ClipsJob>(nameof(ClipsJob)
, job => job.Run(JobCancellationToken.Null),
Cron.MinuteInterval(1), TimeZoneInfo.Local);
5、定时任务程序类,参考:
public void Run(IJobCancellationToken token)
{
{
logger.LogWarning(" 开始采集信息");
logger.LogWarning("结束采集“);
}
}
收工!