Kaveh Kardel
Kaveh Kardel

Reputation: 103

set a specific Date And Time in HangFire

How do I set a specific time? for example 7/2/2021 8:00 AM.
Which methods should I use? Enqueue methods or Schedule methods or AddOrUpdate Methods?

Upvotes: 5

Views: 9570

Answers (3)

Ferdie Venter
Ferdie Venter

Reputation: 21

If you only have the scheduled date:

DateTime dateSchedule = new DateTime(2021, 2, 7);
BackgroundJob.Schedule(job, dateSchedule - DateTime.Now);

Just add date validations so that the scheduled date (dateSchedule) is not in past.

Upvotes: 2

Amr Elgarhy
Amr Elgarhy

Reputation: 68902

From the documentation:

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

Upvotes: 0

Shervin Ivari
Shervin Ivari

Reputation: 2501

Hangfire uses cron schedule expressions. You can set any date-time expression you want. for example

0 8 24 7 * => “At 08:00 on day-of-month 24 in July.”

the following code shows how to use the expression,You can use some online tools for creating expressions like crontab.

RecurringJob.AddOrUpdate(jobId, methodCall, "0 8 24 7 *", TimeZoneInfo.Local);

if you want to execute something once you should use BackgroundJob.

var selectedDate = DateTimeOffset.Parse("2021-07-02 08:00:00");
BackgroundJob.Schedule(() => YourDelayedJob(), selectedDate);

Upvotes: 7

Related Questions