加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-core – 如何在ASP.NET Core中启动Quartz?

发布时间:2020-05-23 21:31:29 所属栏目:asp.Net 来源:互联网
导读:我有以下课程 public class MyEmailService { public async Taskbool SendAdminEmails() { ... } public async Taskbool SendUserEmails() { ... } } public interface I

我有以下课程

public class MyEmailService
 {
    public async Task<bool> SendAdminEmails()
    {
        ...
    }
    public async Task<bool> SendUserEmails()
    {
        ...
    }

 }
 public interface IMyEmailService
 {
    Task<bool> SendAdminEmails();
    Task<bool> SendUserEmails();
 }

我已经安装了最新的Quartz 2.4.1 Nuget package,因为我想在我的Web应用程序中使用轻量级调度程序而没有单独的SQL Server数据库.

我需要安排方法

> SendUserEmails每周一至周一17:00,周二17:00和周二运行.周三17:00
> SendAdminEmails每周星期四09:00,星期五9:00运行

在ASP.NET Core中使用Quartz安排这些方法需要什么代码?我还需要知道如何在ASP.NET Core中启动Quartz,因为互联网上的所有代码示例仍然引用以前版本的ASP.NET.

我可以find a code sample用于以前版本的ASP.NET,但我不知道如何在ASP.NET Core中启动Quartz来开始测试.
我在哪里放置JobScheduler.Start();在ASP.NET核心?

解决方法

TL; DR(完整答案可以在下面找到)

假设工具:Visual Studio 2017 RTM,.NET Core 1.1,.NET Core SDK 1.0,SQL Server Express 2016 LocalDB.

在Web应用程序.csproj中:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <!-- .... existing contents .... -->

  <!-- add the following ItemGroup element,it adds required packages -->
  <ItemGroup>
    <PackageReference Include="Quartz" Version="3.0.0-alpha2" />
    <PackageReference Include="Quartz.Serialization.Json" Version="3.0.0-alpha2" />
  </ItemGroup>

</Project>

在Program类中(默认情况下由Visual Studio搭建):

public class Program
{
    private static IScheduler _scheduler; // add this field

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

        StartScheduler(); // add this line

        host.Run();
    }

    // add this method
    private static void StartScheduler()
    {
        var properties = new NameValueCollection {
            // json serialization is the one supported under .NET Core (binary isn't)
            ["quartz.serializer.type"] = "json",// the following setup of job store is just for example and it didn't change from v2
            // according to your usage scenario though,you definitely need 
            // the ADO.NET job store and not the RAMJobStore.
            ["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX,Quartz",["quartz.jobStore.useProperties"] = "false",["quartz.jobStore.dataSource"] = "default",["quartz.jobStore.tablePrefix"] = "QRTZ_",["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate,["quartz.dataSource.default.provider"] = "SqlServer-41",// SqlServer-41 is the new provider for .NET Core
            ["quartz.dataSource.default.connectionString"] = @"Server=(localdb)MSSQLLocalDB;Database=Quartz;Integrated Security=true"
        };

        var schedulerFactory = new StdSchedulerFactory(properties);
        _scheduler = schedulerFactory.GetScheduler().Result;
        _scheduler.Start().Wait();

        var userEmailsJob = JobBuilder.Create<SendUserEmailsJob>()
            .WithIdentity("SendUserEmails")
            .Build();
        var userEmailsTrigger = TriggerBuilder.Create()
            .WithIdentity("UserEmailsCron")
            .StartNow()
            .WithCronSchedule("0 0 17 ? * MON,TUE,WED")
            .Build();

        _scheduler.ScheduleJob(userEmailsJob,userEmailsTrigger).Wait();

        var adminEmailsJob = JobBuilder.Create<SendAdminEmailsJob>()
            .WithIdentity("SendAdminEmails")
            .Build();
        var adminEmailsTrigger = TriggerBuilder.Create()
            .WithIdentity("AdminEmailsCron")
            .StartNow()
            .WithCronSchedule("0 0 9 ? * THU,FRI")
            .Build();

        _scheduler.ScheduleJob(adminEmailsJob,adminEmailsTrigger).Wait();
    }
}

作业类的示例:

public class SendUserEmailsJob : IJob
{
    public Task Execute(IJobExecutionContext context)
    {
        // an instance of email service can be obtained in different ways,// e.g. service locator,constructor injection (requires custom job factory)
        IMyEmailService emailService = new MyEmailService();

        // delegate the actual work to email service
        return emailService.SendUserEmails();
    }
}

完整答案

Quartz for .NET Core

首先,根据this announcement,你必须使用Quartz的v3,因为它的目标是.NET Core.

目前,只有v3软件包的alpha版本是available on NuGet.看起来团队花了很多精力发布2.5.0,而不是针对.NET Core.尽管如此,在他们的GitHub回购中,主分支已经专注于v3,基本上,open issues for v3 release似乎并不重要,主要是旧的愿望清单项目,恕我直言.由于最近commit activity相当低,我预计v3会在几个月内发布,或者可能是半年 – 但没有人知道.

乔布斯和IIS回收

如果Web应用程序将在IIS下托管,则必须考虑工作进程的回收/卸载行为. ASP.NET Core Web应用程序作为常规.NET Core进程运行,与w3wp.exe分开 – IIS仅用作反向代理.然而,当循环或卸载w3wp.exe的实例时,相关的.NET Core应用程序进程也会发出信号以退出(根据this).

Web应用程序也可以在非IIS反向代理(例如NGINX)后面自行托管,但我会假设您使用IIS,并相应地缩小我的答案.

回收/卸载引入的问题在post referenced by @darin-dimitrov中得到了很好的解释:

>例如,如果在星期五9:00,该进程已关闭,因为几个小时之前它由于不活动而被IIS卸载 – 在该进程再次启动之前不会发送管理员电子邮件.为避免这种情况,请配置IIS以最小化卸载/重新循环(see this answer).

>根据我的经验,上述配置仍然没有100%保证IIS永远不会卸载应用程序.为了100%保证您的进程已启动,您可以设置一个命令,定期向您的应用程序发送请求,从而使其保持活动状态.

>回收/卸载主机进程时,必须正常停止作业,以避免数据损坏.

为什么要在Web应用程序中托管预定作业

尽管存在上面列出的问题,我仍然可以想到将这些电子邮件作业托管在Web应用程序中的一个理由.决定只有一种应用程序模型(ASP.NET).这种方法简化了学习曲线,部署程序,生产监控等.

如果您不想引入后端微服务(这是将电子邮件作业移动到的好地方),那么有必要克服IIS回收/卸载行为,并在Web应用程序中运行Quartz.

或许你有其他原因.

持久的工作商店

在您的方案中,作业执行的状态必须保持在进程外.因此,默认RAMJobStore不适合,您必须使用ADO.NET作业存储.

由于您在问题中提到了SQL Server,我将提供SQL Server数据库的示例设置.

如何启动(并正常停止)调度程序

我假设您使用Visual Studio 2017和最新/最新版本的.NET Core工具.我的是.NET Core Runtime 1.1和.NET Core SDK 1.0.

对于数据库设置示例,我将在SQL Server 2016 Express LocalDB中使用名为Quartz的数据库.数据库设置脚本可以是found here.

首先,向Web应用程序.csproj添加必需的包引用(或者在Visual Studio中使用NuGet包管理器GUI执行此操作):

<Project Sdk="Microsoft.NET.Sdk.Web">

  <!-- .... existing contents .... -->

  <!-- the following ItemGroup adds required packages -->
  <ItemGroup>
    <PackageReference Include="Quartz" Version="3.0.0-alpha2" />
    <PackageReference Include="Quartz.Serialization.Json" Version="3.0.0-alpha2" />
  </ItemGroup>

</Project>

在Migration Guide和V3 Tutorial的帮助下,我们可以弄清楚如何启动和停止调度程序.我更喜欢将它封装在一个单独的类中,让我们将它命名为QuartzStartup.

using System;
using System.Collections.Specialized;
using System.Threading.Tasks;
using Quartz;
using Quartz.Impl;

namespace WebApplication1
{
    // Responsible for starting and gracefully stopping the scheduler.
    public class QuartzStartup
    {
        private IScheduler _scheduler; // after Start,and until shutdown completes,references the scheduler object

        // starts the scheduler,defines the jobs and the triggers
        public void Start()
        {
            if (_scheduler != null)
            {
                throw new InvalidOperationException("Already started.");
            }

            var properties = new NameValueCollection {
                // json serialization is the one supported under .NET Core (binary isn't)
                ["quartz.serializer.type"] = "json",// the following setup of job store is just for example and it didn't change from v2
                ["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX,// SqlServer-41 is the new provider for .NET Core
                ["quartz.dataSource.default.connectionString"] = @"Server=(localdb)MSSQLLocalDB;Database=Quartz;Integrated Security=true"
            };

            var schedulerFactory = new StdSchedulerFactory(properties);
            _scheduler = schedulerFactory.GetScheduler().Result;
            _scheduler.Start().Wait();

            var userEmailsJob = JobBuilder.Create<SendUserEmailsJob>()
                .WithIdentity("SendUserEmails")
                .Build();
            var userEmailsTrigger = TriggerBuilder.Create()
                .WithIdentity("UserEmailsCron")
                .StartNow()
                .WithCronSchedule("0 0 17 ? * MON,WED")
                .Build();

            _scheduler.ScheduleJob(userEmailsJob,userEmailsTrigger).Wait();

            var adminEmailsJob = JobBuilder.Create<SendAdminEmailsJob>()
                .WithIdentity("SendAdminEmails")
                .Build();
            var adminEmailsTrigger = TriggerBuilder.Create()
                .WithIdentity("AdminEmailsCron")
                .StartNow()
                .WithCronSchedule("0 0 9 ? * THU,FRI")
                .Build();

            _scheduler.ScheduleJob(adminEmailsJob,adminEmailsTrigger).Wait();
        }

        // initiates shutdown of the scheduler,and waits until jobs exit gracefully (within allotted timeout)
        public void Stop()
        {
            if (_scheduler == null)
            {
                return;
            }

            // give running jobs 30 sec (for example) to stop gracefully
            if (_scheduler.Shutdown(waitForJobsToComplete: true).Wait(30000)) 
            {
                _scheduler = null;
            }
            else
            {
                // jobs didn't exit in timely fashion - log a warning...
            }
        }
    }
}

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读