We are leaving Russia. We are against aggression and war with Ukraine. It is a tragedy for our nations, it is a nightmare

Best place to call your recuring jobs

Hi guys. I have one question. I need RecurringJob that will do something every hour. Lets say for example send an email. Every tutorial is doing same thing, something like this:

RecurringJob.AddOrUpdate(() => Console.WriteLine("Message goes here."), Cron.Hourly);

And they put that line of code in the Startup.cs/Prgoram.cs. But first of all, I guess we should not call it from Program.cs? But where should we place this line of code, since I dont want use Console.WriteLine but some methode from my services. For example:

RecurringJob.AddOrUpdate(() => _emailService.SendEmail(message), Cron.Hourly);

You can put it in Program.cs. To use RecurringJob the Hangfire setup/initialization code has to have already run. In your example there is message. Where is message coming from? Does it send the same email every hour?

Hi aschenta, thx for your help, I did it like this, in Program.cs.

RecurringJob.AddOrUpdate<IEmailService>(x => x.SendEmail(), Cron.Hourly);

Which is fine for my use case, but let’s say if I need to send some parameter to method, would it be possible?

Technically yes but no. It is recurring. Anything you pass would be hard coded. If you have to determine something I would create a class to perform the logic.

public class SendEmailJob
    private readonly IEmailService _emailService;

    public SendEmailJob(IEmailService emailService)
        _emailService = emailService;

    public void Send()
        // Logic here to determine what to email.


Then it would be

RecurringJob.AddOrUpdate<SendEmailJob>(x => x.Send(), Cron.Hourly);