基本框架:.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文件中配置重復(fù)性的后臺腳本代乃,即設(shè)定某一個時間點去執(zhí)行腳本方法匀泊。
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 = "后臺任務(wù)調(diào)度中心"
});
#else
app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
Authorization = new[] {new BasicAuthAuthorizationFilter(new BasicAuthAuthorizationFilterOptions
{
RequireSsl = false, // 是否需要SSL連接,默認為false
SslRedirect = false, // 是否啟用SSL重定向猎贴,默認為false
LoginCaseSensitive = true, // 登錄名是否區(qū)分大小寫班缎,默認為true
Users = new []
{
new BasicAuthAuthorizationUser
{
Login = "admin", // 管理員登錄名
PasswordClear = "123qwe" // 管理員密碼
}
}
})},
IsReadOnlyFunc = (context) => false, // 設(shè)置儀表盤為可寫模式
DashboardTitle = "后臺任務(wù)調(diào)度中心"
});
#endif
var opt = new RecurringJobOptions { TimeZone = TimeZoneInfo.Local };
var cron = "0 0 7,15 * * ? " ; // 定義每天的七點和十五點執(zhí)行腳本去推送
RecurringJob.AddOrUpdate<IRecurringJobService>("Push",(h) => h.PushAsync(), cron, opt);
}
- 定義執(zhí)行腳本的工作方法
/// <summary>
/// 周期性作業(yè)服務(wù)定義接口
/// </summary>
public interface IRecurringJobService : ITransientDependency
{
/// <summary>
/// 推送
/// </summary>
/// <returns></returns>
Task PushAsync();
}
public class RecurringJobService : IRecurringJobService
{
public RecurringJobService()
{
}
[UnitOfWork]
public async Task PushAsync()
{
// do something...
}
}
- 定義實時執(zhí)行的工作腳本
public interface IPromptJob: ITransientDependency
{
Task ExecuteAsync(DTO args);
}
public class PromptJob: IPromptJob
{
public PromptJob()
{
}
[UnitOfWork]
public async Task ExecuteAsync(DTO args)
{
// do something...
}
}
// 在需要執(zhí)行的地方直接調(diào)用蝴光,主要不要用實現(xiàn)類
BackgroundJob.Enqueue<IPromptJob>(x => x.ExecuteAsync(args));