基本框架:.netcore 6.0、ABP 7.4.0、MySQL
引用文件,添加到实际用的项目中
Abp.HangFire.AspNetCore 7.4.0
Hangfire.Dashboard.BasicAuthorization 1.0.2
Hangfire.MySqlStorage 2.0.3Startup.cs文件中配置Hangfire
public void ConfigureServices(IServiceCollection services)
{
...
AddHandfire(services);
...
}
private void AddHandfire(IServiceCollection services)
{
// Hangfire
services.AddHangfire(config =>
{
var options = new MySqlStorageOptions() {
TablesPrefix = "handfire_"
};
var storage = new MySqlStorage(_appConfiguration.GetConnectionString(FIMSConsts.ConnectionStringName), options);
config.UseStorage(storage);
});
services.AddHangfireServer();
}
- Startup.cs文件中配置重复性的后台脚本,即设定某一个时间点去执行脚本方法。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
...
ConfigureHandfire(app);
...
}
private static void ConfigureHandfire(IApplicationBuilder app)
{
#if DEBUG
app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
DashboardTitle = "后台任务调度中心"
});
#else
app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
Authorization = new[] {new BasicAuthAuthorizationFilter(new BasicAuthAuthorizationFilterOptions
{
RequireSsl = false, // 是否需要SSL连接,默认为false
SslRedirect = false, // 是否启用SSL重定向,默认为false
LoginCaseSensitive = true, // 登录名是否区分大小写,默认为true
Users = new []
{
new BasicAuthAuthorizationUser
{
Login = "admin", // 管理员登录名
PasswordClear = "123qwe" // 管理员密码
}
}
})},
IsReadOnlyFunc = (context) => false, // 设置仪表盘为可写模式
DashboardTitle = "后台任务调度中心"
});
#endif
var opt = new RecurringJobOptions { TimeZone = TimeZoneInfo.Local };
var cron = "0 0 7,15 * * ? " ; // 定义每天的七点和十五点执行脚本去推送
RecurringJob.AddOrUpdate<IRecurringJobService>("Push",(h) => h.PushAsync(), cron, opt);
}
- 定义执行脚本的工作方法
/// <summary>
/// 周期性作业服务定义接口
/// </summary>
public interface IRecurringJobService : ITransientDependency
{
/// <summary>
/// 推送
/// </summary>
/// <returns></returns>
Task PushAsync();
}
public class RecurringJobService : IRecurringJobService
{
public RecurringJobService()
{
}
[UnitOfWork]
public async Task PushAsync()
{
// do something...
}
}
- 定义实时执行的工作脚本
public interface IPromptJob: ITransientDependency
{
Task ExecuteAsync(DTO args);
}
public class PromptJob: IPromptJob
{
public PromptJob()
{
}
[UnitOfWork]
public async Task ExecuteAsync(DTO args)
{
// do something...
}
}
// 在需要执行的地方直接调用,主要不要用实现类
BackgroundJob.Enqueue<IPromptJob>(x => x.ExecuteAsync(args));