7

I am trying to run hangfire recurring job daily on 9.00 AM. Here is what I want to do-

RecurringJob.AddOrUpdate(() => MyMethod(), "* 9 * * *");

Where should I put this line of code?

Sorry if this is a foolish question.

s.k.paul
  • 7,099
  • 28
  • 93
  • 168

4 Answers4

13

Assuming you are using .Net Core, where you can find the file startup.cs. In that you can find a Configure() method. Inside the method you can use that piece of line right after app.UseHangfireDashboard() and app.UseHangfireServer() which is for configuring hangfire dashboard and this is optional. Don't forget to Register Hangfire Services in ConfigureServices() method which can be found in the startup.cs itself.

You can Register Hangfire Services inside ConfigureServices() in Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {    
    /*
    other services
    */

    services.AddHangfire(x => x.UseSqlServerStorage("YOUR_HangfireServerConnectionString"));

    /*
    services.AddMvc()
    */
    }

You can Set Hangfire Cron inside Configure() in Startup.cs

public void Configure(IApplicationBuilder app)
{
    app.UseHangfireDashboard();  
    app.UseHangfireServer();
    RecurringJob.AddOrUpdate(() => MyMethod(), "* 9 * * *");
}

for more refer the link

UPDATE

The cron expression * 9 * * * denotes that the job will fires every minutes after 9 (24 hour format) of system time UTC time.

For creating a recurring job at 9.00 AM Daily, the expression should be 0 9 * * * refer here cron expressions

Farshan
  • 437
  • 5
  • 14
  • thanks for your reply. Unfortunately, I am not using .net core. – s.k.paul Apr 04 '18 at 11:08
  • 2
    For your information, If you don't want the same job running from different instances, You should give a unique identifier while adding the cron like this `RecurringJob.AddOrUpdate("YOUR_UNIQUE_STRING",() => MyMethod(), "* 9 * * *");` – Farshan Apr 04 '18 at 12:19
  • 4
    @s.k.paul Don't forget in Hangfire to daily schedule. Works like this: `RecurringJob.AddOrUpdate(() => MyMethod(), Cron.Daily(9,0));` – Wlad Neto Mar 22 '19 at 17:32
  • 1
    @WladimirTeixeira I have updated the answer with cron expression. That was an unnoticed mistake i copied from the question which makes a remarkable impact on the server. – Farshan Mar 23 '19 at 15:51
3

In asp.net, you can add Microsoft.Owin Middleware and OwinStartup to your project via this nugetpackage and then use the startup.cs to setup hangfire. We always use the Configuration method of Startup.cs file for the hangfire recurring jobs:

            public void Configuration(IAppBuilder app) 
            {
                app.UseHangfireDashboard();
                app.UseHangfireServer();
                RecurringJob.AddOrUpdate(19872.ToString(),() => MyMethod(), Cron.Daily(9, 0));
            }
rodins
  • 306
  • 2
  • 11
  • Just hint for 2023, this is obsolete, use: `builder.Services.AddHangfireServer();` – Sam Feb 28 '23 at 09:15
1
RecurringJob.AddOrUpdate(() => homeCtrl.SendEmail(), Cron.Daily(hour,minute), TimeZoneInfo.Local);

without TimeZoneInfo.Local it will use default UTC time. You have to use TimeZoneInfo.Local always to get your exact time.

        var corn = Cron.Daily();    // "0 0 * * *"  Every night at 12:00 AM

        var corn1 = Cron.Daily(11, 30);   // "30 11 * * *"

        var corn2 = Cron.Daily(12);   // "0 12 * * *"

        var corn3 = Cron.Daily(23,55);  // "55 23 * * *"
Md Shahriar
  • 2,072
  • 22
  • 11
-1

I use a web api endpoint for creating jobs. I always give the recurring job a unique identifier like a guid. That way, if i need to edit the recurring jobs chron expression and can update it via my web api endpoint.

So in the web api i have :-

[HttpPost]
[Microsoft.AspNetCore.Mvc.Route("daily")]
public IActionResult AddOrUpdateDailyReportJob([FromBody]JobOptions options)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    var result = _clientReportJobCreator.AddOrUpdateDailyClientReport(options.JobId, options.ChronExpression);

    return Ok(result);
}

And a service method like this that adds or updates an existing recurring job.

 public JobCreationResult AddOrUpdateDailyClientReport(string jobId, string chronExpression)
        {
            try
            {
                RecurringJob.AddOrUpdate(jobId, () => _clientDailyReportService.Run(), chronExpression);

                var result = new JobCreationResult
                {
                    JobId = jobId,
                    Success = true
                };

                return result;
            }
            catch (Exception ex)
            {
                var result = new JobCreationResult
                {
                    JobId = jobId,
                    Success = false,
                    Errors = new List<string>()
                    {
                        $"{ex.Message}"
                    }
                };

                return result;
            }
        }
Derek
  • 8,300
  • 12
  • 56
  • 88