在 HangFire 中设置特定的日期和时间
set a specific Date And Time in HangFire
如何设置具体时间?例如 7/2/2021 8:00 上午。
我应该使用哪些方法? Enqueue
方法或 Schedule
方法或 AddOrUpdate
方法?
Hangfire 使用 cron 调度表达式。您可以设置任何您想要的日期时间表达式。
例如
0 8 24 7 * =>
“At 08:00 on day-of-month 24 in July.”
下面的代码展示了如何使用表达式,您可以使用一些在线工具来创建表达式,例如crontab。
RecurringJob.AddOrUpdate(jobId, methodCall, "0 8 24 7 *", TimeZoneInfo.Local);
如果你想执行一次你应该使用 BackgroundJob。
var selectedDate = DateTimeOffset.Parse("2021-07-02 08:00:00");
BackgroundJob.Schedule(() => YourDelayedJob(), selectedDate);
来自文档:
Delayed jobs
Delayed jobs are executed only once too, but not
immediately, after a certain time interval.
var jobId = BackgroundJob.Schedule(
() => Console.WriteLine("Delayed!"),
TimeSpan.FromDays(7));
Sometimes you may want to postpone a method invocation; for example,
to send an email to newly registered users a day after their
registration. To do this, just call the BackgroundJob.Schedule method
and pass the desired delay
https://docs.hangfire.io/en/latest/background-methods/calling-methods-with-delay.html
如果您只有预定日期:
DateTime dateSchedule = new DateTime(2021, 2, 7);
BackgroundJob.Schedule(job, dateSchedule - DateTime.Now);
只需添加日期验证,使预定日期 (dateSchedule) 不在过去。
如何设置具体时间?例如 7/2/2021 8:00 上午。
我应该使用哪些方法? Enqueue
方法或 Schedule
方法或 AddOrUpdate
方法?
Hangfire 使用 cron 调度表达式。您可以设置任何您想要的日期时间表达式。 例如
0 8 24 7 * => “At 08:00 on day-of-month 24 in July.”
下面的代码展示了如何使用表达式,您可以使用一些在线工具来创建表达式,例如crontab。
RecurringJob.AddOrUpdate(jobId, methodCall, "0 8 24 7 *", TimeZoneInfo.Local);
如果你想执行一次你应该使用 BackgroundJob。
var selectedDate = DateTimeOffset.Parse("2021-07-02 08:00:00");
BackgroundJob.Schedule(() => YourDelayedJob(), selectedDate);
来自文档:
Delayed jobs
Delayed jobs are executed only once too, but not immediately, after a certain time interval.
var jobId = BackgroundJob.Schedule(
() => Console.WriteLine("Delayed!"),
TimeSpan.FromDays(7));
Sometimes you may want to postpone a method invocation; for example, to send an email to newly registered users a day after their registration. To do this, just call the BackgroundJob.Schedule method and pass the desired delay
https://docs.hangfire.io/en/latest/background-methods/calling-methods-with-delay.html
如果您只有预定日期:
DateTime dateSchedule = new DateTime(2021, 2, 7);
BackgroundJob.Schedule(job, dateSchedule - DateTime.Now);
只需添加日期验证,使预定日期 (dateSchedule) 不在过去。