有没有办法在hangfire中重复安排后台工作? 我尝试过以下但只发射一次。
using (var server = new BackgroundJobServer(options))
{
Console.WriteLine("Hangfire Server started. Press any key to exit...");
// Console.ReadKey();
}
return null;
答案 0 :(得分:1)
使用RecurringJob创建它。 Hangfire Recurring Tasks
RecurringJob.AddOrUpdate("some-id", () => Console.WriteLine(), Cron.Hourly);
答案 1 :(得分:1)
如果您要进行定期计划工作或要在任何特定日期或月份中执行方法。对于Cron表达式,您需要遵循 this
例如:
DateTime date =
DateTime.Parse(ScheduleTime, System.Globalization.CultureInfo.CurrentCulture)
.ToUniversalTime();
var dateString = ScheduleTime.Minute + " " + ScheduleTime.Hour + " " + ScheduleTime.ScheduleDate + " * *";
RecurringJob.AddOrUpdate<IClassController>(
"RecurringName", s => s.Execute(MViewModel),
dateString);
public async Task<bool> Execute(MViewModel mViewModel)
{
try
{
if (mViewModel.ExpiryDate != null && mViewModel.ExpiryDate.Value < DateTime.Now)
{
RecurringJob.RemoveIfExists("RecurringName");
}
else
{
var url = WebConfigurationManager.AppSettings["apiPath"];
string apiUrl = url + "api/VApi/CallAPi";
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(apiUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
"bW9iaWxlYXBw");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var serializedJson = JsonConvert.SerializeObject(mViewModel);
var response = await client.PostAsJsonAsync(apiUrl, serializedJson);
}
}
}
catch (Exception exception)
{
_logger.Log(LogType.Error, ExceptionType.Application, ToString(), exception);
return false;
}
return true;
}
答案 2 :(得分:0)
你可以安排像这样的hangfire工作:
Hangfire.BackgroundJob.Schedule<VerificationEmail>((j) => j.FollowUpVerficationEmail(Email), TimeSpan.FromHours(24));
此处VerificationEmail
是包含FollowUpVerficationEmail
方法的类,每24小时发送一次后续电子邮件。
答案 3 :(得分:0)
您可以这样使用
RecurringJob.AddOrUpdate(/*(optional) job Id*/,() => /*do your stuff here */, /*Cron Expression*/);
1),您可以通过 HangFire的Cron 类选择cron表达式,如下所示
RecurringJob.AddOrUpdate("job1", () => Console.WriteLine("hey"), Cron.Hourly);
2),也可以通过here指定cron表达式,
RecurringJob.AddOrUpdate("job2", () => Console.WriteLine("hey"), "0/10 0 0 ? * * *");
您可以检查here了解更多详细信息。