Reputation: 14926
I need to send a daily summary email to all users but I am unsure where exactly I should trigger it.
I have made a class for sending the emails :
public class SummaryEmailBusiness
{
private MyDbContext _db;
private IEmailSender _emailSender;
public SummaryEmailBusiness(MyDbContext db, IEmailSender emailSender)
{
_db = db;
_emailSender = emailSender;
}
public void SendAllSummaries()
{
foreach(var user in _db.AspNetUsers)
{
//send user a summary
}
}
}
Then in ConfigureServices()
I have registered service and hangfire:
services.AddHangfire(config =>
config.UseSqlServerStorage(Configuration.GetConnectionString("DefaultConnection")));
services.AddTransient<SummaryEmailBusiness>();
And in Configure()
added
app.UseHangfireDashboard();
app.UseHangfireServer();
Now I am stuck. Hang-fire docs say I need to do something like :
RecurringJob.AddOrUpdate(() => SendAllSummaries() , Cron.Daily);
I am not sure how to do this so that the class gets initiated with dependent services injected. How do I reference the SendAllSummaries()
method of instantiated service?
What is best way to do this?
Upvotes: 5
Views: 1831
Reputation: 6864
Hangfire is using CRON expressions. Cron.Daily is shorthand for the CRON expression "0 0 * * *" which is run at midnight daily. If you want to run it at another time of day e.g. 6 am you could do...
RecurringJob.AddOrUpdate<SummaryEmailBusiness>(x => x.SendAllSummaries(), "0 6 * * *");
Read more about CRON Expressions here
Upvotes: 1
Reputation: 101613
All you need to do is just register job (somewhere after calling UseHangfireServer
) like this:
RecurringJob.AddOrUpdate<SummaryEmailBusiness>(x => x.SendAllSummaries(), Cron.Daily);
Doing services.AddHangfire
already registers special JobActivator
which not only resolves job instances from asp.net core DI container, but also creates new scope for each job, which is important in your case, because most likely your MyDbContext
is registered as scoped.
Upvotes: 1