Hcf Hangfire 后台任务组件,封装基于Hangfire后台任务的组件包实现
"Hangfire": {
"WorkerCount": 20,
"ServerName":"xxx",
"Queues":[{"defult"}],
"SchedulePollingInterval":15,//秒
"StorageConnectionString": "Server=.;Database=hcf.admin.dev;User Id=sa;Password=123456;MultipleActiveResultSets=true",
"DashboardUrl": "/hangfire",
"Roles": "",
"Enabled": true
}
RecurringJob.AddOrUpdate("test",()=>writeLog("每20秒执行任务"),"*/20 * * * * *");
public class HangfireJobRunner : IHangfireJobRunner
{
public void Start()
{
//一次性作业
string taskName = "Fire-and-forget tasks";
BackgroundJob.Enqueue(() => Console.WriteLine($"{taskName} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}"));
BackgroundJob.Enqueue<TestHangfireJob>(a => a.GetDashboardUrl(taskName, "测试内容"));
//延迟任务
taskName = "Delayed tasks";
string jobId1 = BackgroundJob.Schedule(() => Console.WriteLine($"{taskName} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},我是job1"), TimeSpan.FromSeconds(10));
string jobId2 = BackgroundJob.Schedule<TestHangfireJob>(a => a.GetDashboardUrl(taskName, "我是job2"), TimeSpan.FromSeconds(10));
//工作流任务
taskName = "Continuations tasks";
BackgroundJob.ContinueJobWith(jobId1, () => Console.WriteLine($"{taskName} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} job1后续的任务"));
BackgroundJob.ContinueJobWith<TestHangfireJob>(jobId2, a => a.GetDashboardUrl(taskName, "测试job2后续的任务"));
//循环任务
taskName = "Recurring tasks 1 min";
RecurringJob.AddOrUpdate("test1", () => Console.WriteLine($"{taskName} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} 1分钟执行一次"), Cron.Minutely, new RecurringJobOptions
{
TimeZone = TimeZoneInfo.Local
});
//RecurringJob.AddOrUpdate<TestHangfireJob>(a => a.GetDashboardUrl(taskName, "1分钟执行一次"), Cron.Minutely, TimeZoneInfo.Local);
RecurringJob.AddOrUpdate<TestHangfireJob>("test2", a => a.GetDashboardUrl(taskName, "test2"), Cron.Minutely, new RecurringJobOptions
{
TimeZone = TimeZoneInfo.Local
});
//taskName = "Recurring tasks 1 sec";
//RecurringJob.AddOrUpdate(() => Console.WriteLine($"{taskName} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} 20秒执行一次"), "*/20 * * * * *");
//RecurringJob.AddOrUpdate<TestHangfireJob>(a => a.GetDashboardUrl(taskName, "20秒执行一次"), "*/20 * * * * *");
}
}
public class TestHangfireJob
{
private readonly IConfiguration _configuration;
public TestHangfireJob(IConfiguration configuration)
{
_configuration = configuration;
}
[Queue("test")]
public string GetDashboardUrl(string name, string content)
{
string dashboardUrl = _configuration["Hcf:Hangfire:DashboardUrl"].CastTo("/hangfire");
Console.WriteLine($"{name} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}, dashboardUrl is {dashboardUrl},content is {content}");
return dashboardUrl;
}
public static string GetDashboardUrl1(string name, string content)
{
string dashboardUrl = "/hangfire1";
Console.WriteLine($"{name} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}, dashboardUrl is {dashboardUrl},content is {content}");
return dashboardUrl;
}
}