使用FluentScheduler-ASP.NET Core MVC [英] Using FluentScheduler - ASP.NET Core MVC
问题描述
我目前使用ASP.NET Core MVC(.NET 4.6.1)进行了简单的网站设置,并且我希望定期进行一些操作,例如每天结束时自动向注册会员发送电子邮件.
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 day to the registered members.
进行搜索后,我遇到了两个常见的解决方案-Quartz.NET和FluentScheduler.
After doing some searching, I came across two common solutions - Quartz.NET and FluentScheduler.
基于此 SO线程,我发现了使用FluentScheduler的方法更易于消化和用于我的简单任务.在将以下代码行快速实现到Program.cs类中之后,我每分钟都会成功发送一封电子邮件(出于测试目的).
Based on this SO thread, I found the approach of using FluentScheduler more easier to digest and use for my simple task. After quickly implementing the following lines of code into my Program.cs class, I had the emails going 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();
}
}
但是,除了发送电子邮件之外,我还需要进行一些后端处理,例如发送邮件时,更新数据库中的用户记录.为此,我通常将实体框架上下文注入到控制器的构造函数中,并使用它来获取/更新SQL记录.
However, now apart from sending emails I also need to do some back-end processing for e.g. updating the user records in the DB when mails are being sent out. For this, I normally inject my Entity Framework Context into the constructor of my controllers and use it to get/update SQL records.
我的问题是,由于我无法真正将这些服务注入main方法中,因此初始化注册表和添加作业以进行调度的合适位置在哪里?
My question is, since I cannot really inject these services into the main method, where would be the appropriate place to initialize the registry and add jobs for scheduling?
感谢您的帮助,我对此有些陌生,因此非常感谢您提供一些指导!
Thanks for the help, I am a little new to this so a little guidance would be much appreciated!
推荐答案
不是在程序的Main函数中,而是在Startup.cs中在app.UseMvc ...
Instead of Program's Main function, I initialized the same in Startup.cs before app.UseMvc..
public void Configure(...., IDependencyObject dependencyObject)
{
....
JobManager.Initialize(new MyRegistry(dependencyObject));
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "api/{controller}/{action}/{id?}");
});
}
我的注册表类如下:
public class MyRegistry: Registry
{
public MyRegistry(IDependencyObject dependencyObject)
{
Schedule(() => new SyncUpJob(dependencyObject)).ToRunNow().AndEvery(10).Seconds();
}
}
我的Job类如下:
public class SyncUpJob: IJob
{
public SyncUpJob(IDependencyObject dependencyObject)
{
DependencyObject= dependencyObject;
}
public IDependencyObject DependencyObject{ get; set; }
public void Execute()
{
// call the method to run weekly here
}
}
这篇关于使用FluentScheduler-ASP.NET Core MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!