Sending a daily summary email using hanging fire and ASP.NET core

I need to send a daily summary message to all users, but I don’t know where exactly I should start it.

I made a class to send 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 a registered service and cheating:

services.AddHangfire(config =>
    config.UseSqlServerStorage(Configuration.GetConnectionString("DefaultConnection")));

services.AddTransient<SummaryEmailBusiness>();

And in Configure()added

app.UseHangfireDashboard();
app.UseHangfireServer();

Now i'm stuck. Hang-fire docs say I need to do something like:

RecurringJob.AddOrUpdate(() =>  SendAllSummaries() , Cron.Daily);

I'm not sure how to do this so that the class starts with dependent services. How to refer to a method SendAllSummaries()for a created service instance?

What is the best way to do this?

+4
source share
2 answers

, , (- UseHangfireServer) :

RecurringJob.AddOrUpdate<SummaryEmailBusiness>(x => x.SendAllSummaries(), Cron.Daily);

services.AddHangfire JobActivator, DI asp.net, , , , , MyDbContext .

+1

Hangfire CRON. Cron.Daily - CRON "0 0 * * *", . , . 6 ...

RecurringJob.AddOrUpdate<SummaryEmailBusiness>(x => x.SendAllSummaries(), "0 6 * * *");

CRON

+1

Source: https://habr.com/ru/post/1695331/


All Articles