https://procodeguide.com/programming/hangfire-in-aspnet-core-schedule-jobs/
安装Hangfire
dotnet add package Hangfire.AspNetCore
//这是将配置存在内存里
dotnet add package Hangfire.MemoryStorage
配置启动项Starup.cs
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.Configure<BookstoreDatabaseSettings>(Configuration.GetSection(nameof(BookstoreDatabaseSettings)));
services.AddSingleton<IBookstoreDatabaseSettings>(sp =>
sp.GetRequiredService<IOptions<BookstoreDatabaseSettings>>().Value);
services.AddSingleton<BookServices>();
//services.AddControllers();
services.AddDbContext<EntityOracleDBContext.EntityOracleDBContext>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddHangfire(configuration => configuration
.UseMemoryStorage());//使用内存
services.AddHangfireServer();//添加hangfire服务
services.AddScoped<CronJob.CronJob>();//注册执行类
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo()
{
Title = "API",
Version = "V1"
});
});
var provider = services.BuildServiceProvider();
return provider;
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env,IServiceProvider provider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//启用中间件服务生成Swagger作为JSON终结点
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "API V1");
});
app.UseMvc();
CronJob.CronJob mongodb = provider.GetService<CronJob.CronJob>();
var options = new BackgroundJobServerOptions { SchedulePollingInterval = TimeSpan.FromSeconds(1.0) };//默认最小间隔为15s,这里设置成1s
app.UseHangfireServer(options);//注入配置
app.UseHangfireDashboard();//启动看板
RecurringJob.AddOrUpdate(() => mongodb.syncs(), Cron.MinuteInterval(2),TimeZoneInfo.Local);//绑定触发器
}
CronJob.cs
using HLZDVideoServer.Entities;
using HLZDVideoServer.MongoDBService;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace HLZDVideoServer.CronJob
{
public class CronJob
{
public EntityOracleDBContext.EntityOracleDBContext context;
private BookServices _bookService;
public CronJob(EntityOracleDBContext.EntityOracleDBContext context, BookServices bookService)
{
this.context = context;
_bookService = bookService;
}
public void syncs()
{
List<BB_FGSSC> bB_FGSSCs = this.context.BB_FGSSCs.ToList().Distinct().ToList();
foreach (BB_FGSSC item in bB_FGSSCs)
{
_bookService.Create(item);
}
}
}
}