set a specific Date And Time in HangFire
Asked Answered
R

3

5

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?

Retouch answered 2/5, 2021 at 17:19 Comment(3)
Should you use the hangfire library? Can't you use DateTime?Cryan
No. HangFire is a library for schedulingRetouch
I found a solution for this. in this way we set a DateTimeOffset to Schedule Method in HangFire. var id = _backgroundJobClient.Schedule(() => Console.WriteLine("Delayed Job"), DateTimeOffset.Now.AddDays(1));Retouch
T
6

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);
Tabbatha answered 3/5, 2021 at 5:42 Comment(5)
Yes that's right. But I want this to be done only once. Doesn't Recurring Method repeat it on this date?Retouch
@SajadKardel you want to do it every month for Example?Tabbatha
No. I want to run only once in a dateRetouch
Apparently it can use the schedule method and get a DateTimeOfSetRetouch
@SajadKardel just updated my answer, Hope it helps, Recurring by self has a repeating life cycle.you have to use BackgroundJobTabbatha
A
2

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.

Amick answered 10/10, 2021 at 15:26 Comment(1)
You can also just use BackgroundJob.Schedule(job, dateSchedule); as the Schedule method also accepts DateTimeOffset.Legroom
C
0

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

Chuvash answered 3/5, 2021 at 7:0 Comment(1)
Yes, but I want to set a specific date and time. Not after a timeRetouch

© 2022 - 2024 — McMap. All rights reserved.