Using FluentScheduler - ASP.NET Core MVC

后端 未结 2 1428
野趣味
野趣味 2021-02-09 01:05

I currently have a simple website setup with ASP.NET Core MVC (.NET 4.6.1), and I would like to periodically do some processes like automatically send emails at the end of every

2条回答
  •  天命终不由人
    2021-02-09 01:59

    You can define all your jobs and their schedules, by subclassing from FluentScheduler Registry class. something like:

    public class JobRegistry : Registry {
    
        public JobRegistry() {
            Schedule().ToRunEvery(1).Days();
            Schedule().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
        }
    }
    

    For injecting dependencies into jobs, you need to implement FluentScheduler IJobFactory interface. GetJobIntance method is called by FluentScheduler for creating job instances. Here you can use any DI library you want; In this sample implementation, I'm going to assume that you use Ninject:

    public class MyNinjectModule : NinjectModule {
        public override void Load()
        {
            Bind().To();
        }
    }
    
    public class JobFactory : IJobFactory {
    
        private IKernel Kernel { get; }
    
        public JobFactory(IKernel kernel)
        {
            Kernel = kernel;
        }
    
        public IJob GetJobInstance() where T : IJob
        {
            return Kernel.Get();
        }
    }
    

    Now you can start your jobs in main method by calling:

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

提交回复
热议问题