Using FluentScheduler - ASP.NET Core MVC

I currently have a simple website setup with ASP.NET Core MVC (.NET 4.6.1), and I would like to periodically perform some processes, such as automatically sending emails at the end of each day to registered members.

After some searching, I came across two common solutions - Quartz.NET and FluentScheduler.

Based on this SO thread , I found the FluentScheduler usage approach easier to digest and use for my simple task. After quickly embedding the following lines of code in my Program.cs class, I had emails that came out successfully every minute (for testing purposes).

public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .Build();

            var registry = new Registry();
            JobManager.Initialize(registry);

            JobManager.AddJob(() => MyEmailService.SendEmail(), s => s
                  .ToRunEvery(1)
                  .Minutes());

            host.Run();

    }
}

, , , . . Entity Framework Context / SQL.

, , ?

, , !

+4
1

, FluentScheduler Registry. - :

public class JobRegistry : Registry {

    public JobRegistry() {
        Schedule<EmailJob>().ToRunEvery(1).Days();
        Schedule<SomeOtherJob>().ToRunEvery(1).Seconds();
    }

}

public class EmailJob : IJob {

    public DbContext Context { get; } // we need this dependency, right?!

    public EmailJob(DbContext context) //constructor injection
    {
        Context = context;
    }

    public void Execute()
    {
        //Job implementation code: send emails to users and update database
    }
}

FluentScheduler IJobFactory. GetJobIntance FluentScheduler . DI, ; , Ninject:

public class MyNinjectModule : NinjectModule {
    public override void Load()
    {
        Bind<DbContext>().To<MyDbContextImplemenation>();
    }
}

public class JobFactory : IJobFactory {

    private IKernel Kernel { get; }

    public JobFactory(IKernel kernel)
    {
        Kernel = kernel;
    }

    public IJob GetJobInstance<T>() where T : IJob
    {
        return Kernel.Get<T>();
    }
}

, :

JobManager.JobFactory = new JobFactory(new StandardKernel(new MyNinjectModule()));
JobManager.Initialize(new JobRegistry());
0

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


All Articles