详解如何使用Quartz.NET和Topshelf做任务调度

一、创建.Net Core 控制台项目
二、安装组件:NLog、Quartz、Quartz.Plugins、Topshelf、Topshelf.NLog、Microsoft.AspNetCore.All
  • 1、安装最新NLog,执行命令install-package NLog。tips:如果使用install-package NLog.Config则自动生成配置文件。

  • 2、安装最新Quartz,执行命令install-package Quartz

  • 3、安装最新Quartz.Plugins,执行命令install-package Quartz.Plugins

  • 4、安装最新Topshelf,执行命令install-package Topshelf

  • 5、安装最新Topshelf.NLog,执行命令install-package Topshelf.NLog。tips:如果使用Log4Net库,则安装Topshelf.Log4Net,命令是install-package Topshelf.Log4Net

  • 6、安装相同版本的Microsoft.AspNetCore.All,执行命令install-package Microsoft.AspNetCore.All -version 2.1.0。tips:安装 .net core 2.1 完整包,是为了使用common(GetSettings)方法读取配置文件的内容,代码如下:

          public static class GetSettings
          {
              private static string GetCustomSettings(string getSection, string key)
              {
                  var config = new ConfigurationBuilder()
                      .AddInMemoryCollection()
                      .SetBasePath(Directory.GetCurrentDirectory())
                      .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                      .Build();
                  return config.GetSection(getSection).GetValue(key, string.Empty);
              }
    
              public static string GetTestStr => GetCustomSettings("ConnectionStrings", "TestDB");
    
          }
    
详解如何使用Quartz.NET和Topshelf做任务调度_第1张图片
安装完成后包效果图
三、创建配置文件:NLog.config、quartz.config和XML文件,quartz_jobs.xml。并且给三个文件填充内容。
1、给nlog.config(建议全部小写)填充内容。(nlog官方GitHub地址:https://github.com/NLog/NLog.web/wiki)
  • Nlog官方使用实例:https://github.com/NLog/NLog/blob/dev/examples/NLogDemo/NLog.config
  • 我写的NLog配置完整教程:https://www.jianshu.com/p/6b005acafa83
  • 如果将控制台应用程序部署成服务后,无法记录日志,请直接将连接字符串写到Nlog配置文件中

参考内容:




  
  
  

  
  

    

    

    
    
      
      
      
      
      
    

    


    
    

    

    



    
      ${var:connectionString}
      
        INSERT INTO [dbo].[ServiceLog]
        ([Application]
        ,[Level]
        ,[Logger]
        ,[Callsite]
        ,[LineNum]
        ,[RequestBody]
        ,[OriginalRequestBody]
        ,[RequestURL]
        ,[ApiUrl]
        ,[Response]
        ,[IsSuccess]
        ,[SQLStatement]
        ,[Action]
        ,[Message]
        ,[Exception]
        ,[Operatingtime]
        ,[ServerAddress]
        ,[RemoteAddress]
        ,[Method]
        ,[EventTimeBegin]
        ,[EventTimeEnd]
        ,[EventTimeSpend]
        ,[SourceFileName]
        ,[UserName])
        VALUES
        (@application
        ,@levels
        ,@logger
        ,@callSite
        ,@lineNum
        ,@requestBody
        ,@originalRequestBody
        ,@requestURL
        ,@apiUrl
        ,@response
        ,@isSuccess
        ,@sqlStatement
        ,@action
        ,@message
        ,@exception
        ,@operatingtime
        ,@serverAddress
        ,@remoteAddress
        ,@method
        ,@eventTimeBegin
        ,@eventTimeEnd
        ,@eventTimeSpend
        ,@sourceFileName
        ,@userName
        );
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    

    
      ${var:connectionString}
      
        INSERT INTO [dbo].[ServiceLog]
        ([Application]
        ,[Level]
        ,[Logger]
        ,[Callsite]
        ,[LineNum]
        ,[RequestBody]
        ,[OriginalRequestBody]
        ,[RequestURL]
        ,[ApiUrl]
        ,[Response]
        ,[IsSuccess]
        ,[SQLStatement]
        ,[Action]
        ,[Message]
        ,[Exception]
        ,[Operatingtime]
        ,[ServerAddress]
        ,[RemoteAddress]
        ,[Method]
        ,[EventTimeBegin]
        ,[EventTimeEnd]
        ,[EventTimeSpend]
        ,[SourceFileName]
        ,[UserName])
        VALUES
        (@application
        ,@levels
        ,@logger
        ,@callSite
        ,@lineNum
        ,@requestBody
        ,@originalRequestBody
        ,@requestURL
        ,@apiUrl
        ,@response
        ,@isSuccess
        ,@sqlStatement
        ,@action
        ,@message
        ,@exception
        ,@operatingtime
        ,@serverAddress
        ,@remoteAddress
        ,@method
        ,@eventTimeBegin
        ,@eventTimeEnd
        ,@eventTimeSpend
        ,@sourceFileName
        ,@userName
        );
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    

  

  
    

    

    
    
    
    
    
    
    
    
    

  

2、给quartz.config填充内容
    # You can configure your scheduler in either  configuration section
    # or in quartz properties file
    # Configuration section has precedence

    quartz.scheduler.instanceName = QuartzTest

    # configure thread pool info(tips:threadCount = 10,最大10个线程)
    quartz.threadPool.type = Quartz.Simpl.SimpleThreadPool, Quartz
    quartz.threadPool.threadCount = 10
    quartz.threadPool.threadPriority = Normal

    # job initialization plugin handles our xml reading, without it defaults are used
    quartz.plugin.xml.type = Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz.Plugins
    quartz.plugin.xml.fileNames = ~/quartz_jobs.xml

    # export this server to remoting context
    #quartz.scheduler.exporter.type = Quartz.Simpl.RemotingSchedulerExporter, Quartz
    #quartz.scheduler.exporter.port = 555
    #quartz.scheduler.exporter.bindName = QuartzScheduler
    #quartz.scheduler.exporter.channelType = tcp
    #quartz.scheduler.exporter.channelName = httpQuartz
  • 如下版本是将quartz.net运行状况记录到数据库的

      # You can configure your scheduler in either  configuration section
      # or in quartz properties file
      # Configuration section has precedence
    
      quartz.scheduler.instanceName = QuartzTest
    
      # configure thread pool info
      quartz.threadPool.type = Quartz.Simpl.SimpleThreadPool, Quartz
      quartz.threadPool.threadCount = 1
      quartz.threadPool.threadPriority = Normal
    
      # job initialization plugin handles our xml reading, without it defaults are used
      quartz.plugin.xml.type = Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz.Plugins
      quartz.plugin.xml.fileNames = ~/quartz_jobs.xml
    
      #数据连接字符串
      quartz.dataSource.myDS.connectionString=Database=Quartz;Server=localhost;User ID=sa;Password=123456;Pooling=true;Max Pool Size=32767;Min Pool Size=0;
      #数据库类型
      quartz.dataSource.myDS.provider=SqlServer
      #设置存储类型
      quartz.jobStore.type=Quartz.Impl.AdoJobStore.JobStoreTX, Quartz
      #驱动类型
      quartz.jobStore.driverDelegateType=Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz
      #数据源名称,于 quartz.dataSource 的属性名一样
      quartz.jobStore.dataSource=myDS
      #JobDataMaps 中的值只能是字符串,具体可以看官方推荐这样设置的原因
      quartz.jobStore.useProperties=true
      #数据存储序列号方式,在.net core 环境下用json格式报错
      quartz.serializer.type=binary
      #是否是集群模式
      quartz.jobStore.clustered=true
      #自动生成唯一的instanceId
      quartz.scheduler.instanceId=AUTO
    
      # export this server to remoting context
      #quartz.scheduler.exporter.type = Quartz.Simpl.RemotingSchedulerExporter, Quartz
      #quartz.scheduler.exporter.port = 555
      #quartz.scheduler.exporter.bindName = QuartzScheduler
      #quartz.scheduler.exporter.channelType = tcp
      #quartz.scheduler.exporter.channelName = httpQuartz
    
  • SQL server数据库脚本(其他版本可以去GitHub下载,tips该脚本最近更新都是一两年前了,https://github.com/quartznet/quartznet/tree/master/database/tables)

    USE [Quartz]
    GO

    IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_QRTZ_TRIGGERS_QRTZ_JOB_DETAILS]') AND OBJECTPROPERTY(id, N'ISFOREIGNKEY') = 1)
    ALTER TABLE [dbo].[QRTZ_TRIGGERS] DROP CONSTRAINT FK_QRTZ_TRIGGERS_QRTZ_JOB_DETAILS
    GO

    IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_QRTZ_CRON_TRIGGERS_QRTZ_TRIGGERS]') AND OBJECTPROPERTY(id, N'ISFOREIGNKEY') = 1)
    ALTER TABLE [dbo].[QRTZ_CRON_TRIGGERS] DROP CONSTRAINT FK_QRTZ_CRON_TRIGGERS_QRTZ_TRIGGERS
    GO

    IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_QRTZ_SIMPLE_TRIGGERS_QRTZ_TRIGGERS]') AND OBJECTPROPERTY(id, N'ISFOREIGNKEY') = 1)
    ALTER TABLE [dbo].[QRTZ_SIMPLE_TRIGGERS] DROP CONSTRAINT FK_QRTZ_SIMPLE_TRIGGERS_QRTZ_TRIGGERS
    GO

    IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_QRTZ_SIMPROP_TRIGGERS_QRTZ_TRIGGERS]') AND OBJECTPROPERTY(id, N'ISFOREIGNKEY') = 1)
    ALTER TABLE [dbo].[QRTZ_SIMPROP_TRIGGERS] DROP CONSTRAINT FK_QRTZ_SIMPROP_TRIGGERS_QRTZ_TRIGGERS
    GO

    IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_QRTZ_JOB_LISTENERS_QRTZ_JOB_DETAILS]') AND parent_object_id = OBJECT_ID(N'[dbo].[QRTZ_JOB_LISTENERS]'))
    ALTER TABLE [dbo].[QRTZ_JOB_LISTENERS] DROP CONSTRAINT [FK_QRTZ_JOB_LISTENERS_QRTZ_JOB_DETAILS]

    IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_QRTZ_TRIGGER_LISTENERS_QRTZ_TRIGGERS]') AND parent_object_id = OBJECT_ID(N'[dbo].[QRTZ_TRIGGER_LISTENERS]'))
    ALTER TABLE [dbo].[QRTZ_TRIGGER_LISTENERS] DROP CONSTRAINT [FK_QRTZ_TRIGGER_LISTENERS_QRTZ_TRIGGERS]


    IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[QRTZ_CALENDARS]') AND OBJECTPROPERTY(id, N'ISUSERTABLE') = 1)
    DROP TABLE [dbo].[QRTZ_CALENDARS]
    GO

    IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[QRTZ_CRON_TRIGGERS]') AND OBJECTPROPERTY(id, N'ISUSERTABLE') = 1)
    DROP TABLE [dbo].[QRTZ_CRON_TRIGGERS]
    GO

    IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[QRTZ_BLOB_TRIGGERS]') AND OBJECTPROPERTY(id, N'ISUSERTABLE') = 1)
    DROP TABLE [dbo].[QRTZ_BLOB_TRIGGERS]
    GO

    IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[QRTZ_FIRED_TRIGGERS]') AND OBJECTPROPERTY(id, N'ISUSERTABLE') = 1)
    DROP TABLE [dbo].[QRTZ_FIRED_TRIGGERS]
    GO

    IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[QRTZ_PAUSED_TRIGGER_GRPS]') AND OBJECTPROPERTY(id, N'ISUSERTABLE') = 1)
    DROP TABLE [dbo].[QRTZ_PAUSED_TRIGGER_GRPS]
    GO

    IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[QRTZ_JOB_LISTENERS]') AND type in (N'U'))
    DROP TABLE [dbo].[QRTZ_JOB_LISTENERS]

    IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[QRTZ_SCHEDULER_STATE]') AND OBJECTPROPERTY(id, N'ISUSERTABLE') = 1)
    DROP TABLE [dbo].[QRTZ_SCHEDULER_STATE]
    GO

    IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[QRTZ_LOCKS]') AND OBJECTPROPERTY(id, N'ISUSERTABLE') = 1)
    DROP TABLE [dbo].[QRTZ_LOCKS]
    GO
    IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[QRTZ_TRIGGER_LISTENERS]') AND type in (N'U'))
    DROP TABLE [dbo].[QRTZ_TRIGGER_LISTENERS]


    IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[QRTZ_JOB_DETAILS]') AND OBJECTPROPERTY(id, N'ISUSERTABLE') = 1)
    DROP TABLE [dbo].[QRTZ_JOB_DETAILS]
    GO

    IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[QRTZ_SIMPLE_TRIGGERS]') AND OBJECTPROPERTY(id, N'ISUSERTABLE') = 1)
    DROP TABLE [dbo].[QRTZ_SIMPLE_TRIGGERS]
    GO

    IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[QRTZ_SIMPROP_TRIGGERS]') AND OBJECTPROPERTY(id, N'ISUSERTABLE') = 1)
    DROP TABLE [dbo].QRTZ_SIMPROP_TRIGGERS
    GO

    IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[QRTZ_TRIGGERS]') AND OBJECTPROPERTY(id, N'ISUSERTABLE') = 1)
    DROP TABLE [dbo].[QRTZ_TRIGGERS]
    GO

    CREATE TABLE [dbo].[QRTZ_CALENDARS] (
      [SCHED_NAME] [NVARCHAR] (120)  NOT NULL ,
      [CALENDAR_NAME] [NVARCHAR] (200)  NOT NULL ,
      [CALENDAR] [VARBINARY](MAX) NOT NULL
    )
    GO

    CREATE TABLE [dbo].[QRTZ_CRON_TRIGGERS] (
      [SCHED_NAME] [NVARCHAR] (120)  NOT NULL ,
      [TRIGGER_NAME] [NVARCHAR] (150)  NOT NULL ,
      [TRIGGER_GROUP] [NVARCHAR] (150)  NOT NULL ,
      [CRON_EXPRESSION] [NVARCHAR] (120)  NOT NULL ,
      [TIME_ZONE_ID] [NVARCHAR] (80) 
    )
    GO

    CREATE TABLE [dbo].[QRTZ_FIRED_TRIGGERS] (
      [SCHED_NAME] [NVARCHAR] (120)  NOT NULL ,
      [ENTRY_ID] [NVARCHAR] (140)  NOT NULL ,
      [TRIGGER_NAME] [NVARCHAR] (150)  NOT NULL ,
      [TRIGGER_GROUP] [NVARCHAR] (150)  NOT NULL ,
      [INSTANCE_NAME] [NVARCHAR] (200)  NOT NULL ,
      [FIRED_TIME] [BIGINT] NOT NULL ,
      [SCHED_TIME] [BIGINT] NOT NULL ,
      [PRIORITY] [INTEGER] NOT NULL ,
      [STATE] [NVARCHAR] (16)  NOT NULL,
      [JOB_NAME] [NVARCHAR] (150)  NULL ,
      [JOB_GROUP] [NVARCHAR] (150)  NULL ,
      [IS_NONCONCURRENT] BIT  NULL ,
      [REQUESTS_RECOVERY] BIT  NULL 
    )
    GO

    CREATE TABLE [dbo].[QRTZ_PAUSED_TRIGGER_GRPS] (
      [SCHED_NAME] [NVARCHAR] (120)  NOT NULL ,
      [TRIGGER_GROUP] [NVARCHAR] (150)  NOT NULL 
    )
    GO

    CREATE TABLE [dbo].[QRTZ_SCHEDULER_STATE] (
      [SCHED_NAME] [NVARCHAR] (120)  NOT NULL ,
      [INSTANCE_NAME] [NVARCHAR] (200)  NOT NULL ,
      [LAST_CHECKIN_TIME] [BIGINT] NOT NULL ,
      [CHECKIN_INTERVAL] [BIGINT] NOT NULL
    )
    GO

    CREATE TABLE [dbo].[QRTZ_LOCKS] (
      [SCHED_NAME] [NVARCHAR] (120)  NOT NULL ,
      [LOCK_NAME] [NVARCHAR] (40)  NOT NULL 
    )
    GO

    CREATE TABLE [dbo].[QRTZ_JOB_DETAILS] (
      [SCHED_NAME] [NVARCHAR] (120)  NOT NULL ,
      [JOB_NAME] [NVARCHAR] (150)  NOT NULL ,
      [JOB_GROUP] [NVARCHAR] (150)  NOT NULL ,
      [DESCRIPTION] [NVARCHAR] (250) NULL ,
      [JOB_CLASS_NAME] [NVARCHAR] (250)  NOT NULL ,
      [IS_DURABLE] BIT  NOT NULL ,
      [IS_NONCONCURRENT] BIT  NOT NULL ,
      [IS_UPDATE_DATA] BIT  NOT NULL ,
      [REQUESTS_RECOVERY] BIT  NOT NULL ,
      [JOB_DATA] [VARBINARY](MAX) NULL
    )
    GO

    CREATE TABLE [dbo].[QRTZ_SIMPLE_TRIGGERS] (
      [SCHED_NAME] [NVARCHAR] (120)  NOT NULL ,
      [TRIGGER_NAME] [NVARCHAR] (150)  NOT NULL ,
      [TRIGGER_GROUP] [NVARCHAR] (150)  NOT NULL ,
      [REPEAT_COUNT] [INTEGER] NOT NULL ,
      [REPEAT_INTERVAL] [BIGINT] NOT NULL ,
      [TIMES_TRIGGERED] [INTEGER] NOT NULL
    )
    GO

    CREATE TABLE [dbo].[QRTZ_SIMPROP_TRIGGERS] (
      [SCHED_NAME] [NVARCHAR] (120)  NOT NULL ,
      [TRIGGER_NAME] [NVARCHAR] (150)  NOT NULL ,
      [TRIGGER_GROUP] [NVARCHAR] (150)  NOT NULL ,
      [STR_PROP_1] [NVARCHAR] (512) NULL,
      [STR_PROP_2] [NVARCHAR] (512) NULL,
      [STR_PROP_3] [NVARCHAR] (512) NULL,
      [INT_PROP_1] [INT] NULL,
      [INT_PROP_2] [INT] NULL,
      [LONG_PROP_1] [BIGINT] NULL,
      [LONG_PROP_2] [BIGINT] NULL,
      [DEC_PROP_1] [NUMERIC] (13,4) NULL,
      [DEC_PROP_2] [NUMERIC] (13,4) NULL,
      [BOOL_PROP_1] BIT NULL,
      [BOOL_PROP_2] BIT NULL,
      [TIME_ZONE_ID] [NVARCHAR] (80) NULL 
    )
    GO

    CREATE TABLE [dbo].[QRTZ_BLOB_TRIGGERS] (
      [SCHED_NAME] [NVARCHAR] (120)  NOT NULL ,
      [TRIGGER_NAME] [NVARCHAR] (150)  NOT NULL ,
      [TRIGGER_GROUP] [NVARCHAR] (150)  NOT NULL ,
      [BLOB_DATA] [VARBINARY](MAX) NULL
    )
    GO

    CREATE TABLE [dbo].[QRTZ_TRIGGERS] (
      [SCHED_NAME] [NVARCHAR] (120)  NOT NULL ,
      [TRIGGER_NAME] [NVARCHAR] (150)  NOT NULL ,
      [TRIGGER_GROUP] [NVARCHAR] (150)  NOT NULL ,
      [JOB_NAME] [NVARCHAR] (150)  NOT NULL ,
      [JOB_GROUP] [NVARCHAR] (150)  NOT NULL ,
      [DESCRIPTION] [NVARCHAR] (250) NULL ,
      [NEXT_FIRE_TIME] [BIGINT] NULL ,
      [PREV_FIRE_TIME] [BIGINT] NULL ,
      [PRIORITY] [INTEGER] NULL ,
      [TRIGGER_STATE] [NVARCHAR] (16)  NOT NULL ,
      [TRIGGER_TYPE] [NVARCHAR] (8)  NOT NULL ,
      [START_TIME] [BIGINT] NOT NULL ,
      [END_TIME] [BIGINT] NULL ,
      [CALENDAR_NAME] [NVARCHAR] (200)  NULL ,
      [MISFIRE_INSTR] [INTEGER] NULL ,
      [JOB_DATA] [VARBINARY](MAX) NULL
    )
    GO

    ALTER TABLE [dbo].[QRTZ_CALENDARS] WITH NOCHECK ADD
      CONSTRAINT [PK_QRTZ_CALENDARS] PRIMARY KEY  CLUSTERED
      (
        [SCHED_NAME],
        [CALENDAR_NAME]
      ) 
    GO

    ALTER TABLE [dbo].[QRTZ_CRON_TRIGGERS] WITH NOCHECK ADD
      CONSTRAINT [PK_QRTZ_CRON_TRIGGERS] PRIMARY KEY  CLUSTERED
      (
        [SCHED_NAME],
        [TRIGGER_NAME],
        [TRIGGER_GROUP]
      ) 
    GO

    ALTER TABLE [dbo].[QRTZ_FIRED_TRIGGERS] WITH NOCHECK ADD
      CONSTRAINT [PK_QRTZ_FIRED_TRIGGERS] PRIMARY KEY  CLUSTERED
      (
        [SCHED_NAME],
        [ENTRY_ID]
      ) 
    GO

    ALTER TABLE [dbo].[QRTZ_PAUSED_TRIGGER_GRPS] WITH NOCHECK ADD
      CONSTRAINT [PK_QRTZ_PAUSED_TRIGGER_GRPS] PRIMARY KEY  CLUSTERED
      (
        [SCHED_NAME],
        [TRIGGER_GROUP]
      ) 
    GO

    ALTER TABLE [dbo].[QRTZ_SCHEDULER_STATE] WITH NOCHECK ADD
      CONSTRAINT [PK_QRTZ_SCHEDULER_STATE] PRIMARY KEY  CLUSTERED
      (
        [SCHED_NAME],
        [INSTANCE_NAME]
      ) 
    GO

    ALTER TABLE [dbo].[QRTZ_LOCKS] WITH NOCHECK ADD
      CONSTRAINT [PK_QRTZ_LOCKS] PRIMARY KEY  CLUSTERED
      (
        [SCHED_NAME],
        [LOCK_NAME]
      ) 
    GO

    ALTER TABLE [dbo].[QRTZ_JOB_DETAILS] WITH NOCHECK ADD
      CONSTRAINT [PK_QRTZ_JOB_DETAILS] PRIMARY KEY  CLUSTERED
      (
        [SCHED_NAME],
        [JOB_NAME],
        [JOB_GROUP]
      ) 
    GO

    ALTER TABLE [dbo].[QRTZ_SIMPLE_TRIGGERS] WITH NOCHECK ADD
      CONSTRAINT [PK_QRTZ_SIMPLE_TRIGGERS] PRIMARY KEY  CLUSTERED
      (
        [SCHED_NAME],
        [TRIGGER_NAME],
        [TRIGGER_GROUP]
      ) 
    GO

    ALTER TABLE [dbo].[QRTZ_SIMPROP_TRIGGERS] WITH NOCHECK ADD
      CONSTRAINT [PK_QRTZ_SIMPROP_TRIGGERS] PRIMARY KEY  CLUSTERED
      (
        [SCHED_NAME],
        [TRIGGER_NAME],
        [TRIGGER_GROUP]
      ) 
    GO

    ALTER TABLE [dbo].[QRTZ_TRIGGERS] WITH NOCHECK ADD
      CONSTRAINT [PK_QRTZ_TRIGGERS] PRIMARY KEY  CLUSTERED
      (
        [SCHED_NAME],
        [TRIGGER_NAME],
        [TRIGGER_GROUP]
      ) 
    GO

    ALTER TABLE [dbo].QRTZ_BLOB_TRIGGERS WITH NOCHECK ADD
      CONSTRAINT [PK_QRTZ_BLOB_TRIGGERS] PRIMARY KEY  CLUSTERED
      (
        [SCHED_NAME],
        [TRIGGER_NAME],
        [TRIGGER_GROUP]
      ) 
    GO

    ALTER TABLE [dbo].[QRTZ_CRON_TRIGGERS] ADD
      CONSTRAINT [FK_QRTZ_CRON_TRIGGERS_QRTZ_TRIGGERS] FOREIGN KEY
      (
        [SCHED_NAME],
        [TRIGGER_NAME],
        [TRIGGER_GROUP]
      ) REFERENCES [dbo].[QRTZ_TRIGGERS] (
        [SCHED_NAME],
        [TRIGGER_NAME],
        [TRIGGER_GROUP]
      ) ON DELETE CASCADE
    GO

    ALTER TABLE [dbo].[QRTZ_SIMPLE_TRIGGERS] ADD
      CONSTRAINT [FK_QRTZ_SIMPLE_TRIGGERS_QRTZ_TRIGGERS] FOREIGN KEY
      (
        [SCHED_NAME],
        [TRIGGER_NAME],
        [TRIGGER_GROUP]
      ) REFERENCES [dbo].[QRTZ_TRIGGERS] (
        [SCHED_NAME],
        [TRIGGER_NAME],
        [TRIGGER_GROUP]
      ) ON DELETE CASCADE
    GO

    ALTER TABLE [dbo].[QRTZ_SIMPROP_TRIGGERS] ADD
      CONSTRAINT [FK_QRTZ_SIMPROP_TRIGGERS_QRTZ_TRIGGERS] FOREIGN KEY
      (
        [SCHED_NAME],
        [TRIGGER_NAME],
        [TRIGGER_GROUP]
      ) REFERENCES [dbo].[QRTZ_TRIGGERS] (
        [SCHED_NAME],
        [TRIGGER_NAME],
        [TRIGGER_GROUP]
      ) ON DELETE CASCADE
    GO

    ALTER TABLE [dbo].[QRTZ_TRIGGERS] ADD
      CONSTRAINT [FK_QRTZ_TRIGGERS_QRTZ_JOB_DETAILS] FOREIGN KEY
      (
        [SCHED_NAME],
        [JOB_NAME],
        [JOB_GROUP]
      ) REFERENCES [dbo].[QRTZ_JOB_DETAILS] (
        [SCHED_NAME],
        [JOB_NAME],
        [JOB_GROUP]
      )
    GO

    CREATE INDEX IDX_QRTZ_T_J ON QRTZ_TRIGGERS(SCHED_NAME,JOB_NAME,JOB_GROUP)
    CREATE INDEX IDX_QRTZ_T_JG ON QRTZ_TRIGGERS(SCHED_NAME,JOB_GROUP)
    CREATE INDEX IDX_QRTZ_T_C ON QRTZ_TRIGGERS(SCHED_NAME,CALENDAR_NAME)
    CREATE INDEX IDX_QRTZ_T_G ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_GROUP)
    CREATE INDEX IDX_QRTZ_T_STATE ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_STATE)
    CREATE INDEX IDX_QRTZ_T_N_STATE ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP,TRIGGER_STATE)
    CREATE INDEX IDX_QRTZ_T_N_G_STATE ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_GROUP,TRIGGER_STATE)
    CREATE INDEX IDX_QRTZ_T_NEXT_FIRE_TIME ON QRTZ_TRIGGERS(SCHED_NAME,NEXT_FIRE_TIME)
    CREATE INDEX IDX_QRTZ_T_NFT_ST ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_STATE,NEXT_FIRE_TIME)
    CREATE INDEX IDX_QRTZ_T_NFT_MISFIRE ON QRTZ_TRIGGERS(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME)
    CREATE INDEX IDX_QRTZ_T_NFT_ST_MISFIRE ON QRTZ_TRIGGERS(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME,TRIGGER_STATE)
    CREATE INDEX IDX_QRTZ_T_NFT_ST_MISFIRE_GRP ON QRTZ_TRIGGERS(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME,TRIGGER_GROUP,TRIGGER_STATE)

    CREATE INDEX IDX_QRTZ_FT_TRIG_INST_NAME ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,INSTANCE_NAME)
    CREATE INDEX IDX_QRTZ_FT_INST_JOB_REQ_RCVRY ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,INSTANCE_NAME,REQUESTS_RECOVERY)
    CREATE INDEX IDX_QRTZ_FT_J_G ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,JOB_NAME,JOB_GROUP)
    CREATE INDEX IDX_QRTZ_FT_JG ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,JOB_GROUP)
    CREATE INDEX IDX_QRTZ_FT_T_G ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
    CREATE INDEX IDX_QRTZ_FT_TG ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,TRIGGER_GROUP)
    GO
3、给quartz_jobs.xml填充内容(参考地址:https://www.cnblogs.com/wuzhixiong/p/10670288.html)
  

    
      true
    

    

      
      
        TestJob
        Test
        测试任务
        JobServiceDemo.TestJob,JobServiceDemo
        true
        false
      
      
        
          TestJobTrigger
          TestTrigger
          TestJob
          Test
          2019-04-04T00:00:00+08:00
          0/3 * * * * ?
        
      

    
  
带备注的文件
  

  

  

    
      true
    

    
      
      
        
        SampleJob
        
        SampleGroup
        
        SampleJob测试
        
        QuartzDemo.SampleJob,QuartzDemo
        true
        false
      

      
      
        
        
          
          TestJobTrigger
          
          Test
          
          TestJobTriggerDescription
          
          SampleJob
          
          SampleGroup
          
          2015-01-22T00:00:00+08:00
          
          0/3 * * * * ?
        
      

    
  
四、使用Topshelf调度任务(或者说是:结合topshelf调度任务)

新建ServiceRunner服务运行类用于控制调度器的启动,停止,暂停,恢复运行4个接口方法,代码如下:

    using Quartz;
    using Quartz.Impl;
    using Topshelf;

    namespace SyncCIS.Job
    {
        public sealed class ServiceRunner : ServiceControl, ServiceSuspend
        {
            //调度器
            private readonly IScheduler scheduler;
            public ServiceRunner()
            {
                scheduler = StdSchedulerFactory.GetDefaultScheduler().GetAwaiter().GetResult();
            }
            //开始
            public bool Start(HostControl hostControl)
            {
                scheduler.Start();
                return true;
            }
            //停止
            public bool Stop(HostControl hostControl)
            {
                scheduler.Shutdown(false);
                return true;
            }
            //恢复所有
            public bool Continue(HostControl hostControl)
            {
                scheduler.ResumeAll();
                return true;
            }
            //暂停所有
            public bool Pause(HostControl hostControl)
            {
                scheduler.PauseAll();
                return true;
            }
        }
    }
五、配置windows service服务(程序入口),采用的通用模式
    class Program
    {
        static void Main(string[] args)
        {
            NLog.LogManager.LoadConfiguration("NLog.config").GetCurrentClassLogger();
            NLog.LogManager.Configuration.Variables["connectionString"] = GetSettings.GetCRMLogStr;

            HostFactory.Run(x =>
            {
                x.UseNLog();
                x.Service(s => {
                    s.ConstructUsing(name => new ServiceRunner());
                    s.WhenStarted((tc, hc) => tc.Start(hc));
                    s.WhenStopped((tc, hc) => tc.Stop(hc));
                    s.WhenContinued((tc, hc) => tc.Continue(hc));
                    s.WhenPaused((tc, hc) => tc.Pause(hc));
                });

                x.RunAsLocalService();
                x.StartAutomaticallyDelayed();

                x.SetDescription("填写服务描述");
                x.SetDisplayName("填写服务显示名称");
                x.SetServiceName("填写服务名称");

                x.EnablePauseAndContinue();
            });
        }
    }
六、实现IJob接口,编写单个服务
    using System;
    using Microsoft.IdentityModel.Logging;

    /// 
    /// A sample job that just prints info on console for demostration purposes.
    /// 
    public class SampleJob : IJob
    {
        //private static readonly ILog logger = LogManager.GetLogger(typeof(SampleJob));

        /// 
        /// Called by the  when a 
        /// fires that is associated with the .
        /// 
        /// 
        /// The implementation may wish to set a  result object on the 
        /// JobExecutionContext before this method exits.  The result itself
        /// is meaningless to Quartz, but may be informative to 
        /// s or 
        /// s that are watching the job's 
        /// execution.
        /// 
        /// The execution context.
        public void Execute(IJobExecutionContext context)
        {
            LogHelper.Info("SampleJob running...");
            //Thread.Sleep(TimeSpan.FromSeconds(5));
            Console.WriteLine("111111111111111111111");
            LogHelper.Info("SampleJob run finished.");
        }
    }

如果上面的方法不行,可以使用下面的代码

    public Task Execute(IJobExecutionContext context)
    {
        Console.WriteLine("test");
        return Task.FromResult(true);
    }
七、使用Topshelf安装成Windows服务运行(以管理员身份打开Cmd,找到EXE文件,进行安装启动卸载)
详解如何使用Quartz.NET和Topshelf做任务调度_第2张图片
.net core 应用程序发布配置
    安装:程序绝对路径Demo.exe install
    启动:程序绝对路径Demo.exe start
    卸载:程序绝对路径Demo.exe uninstall
八、Quartz配置说明
1、job 任务

其实就是1.x版本中的,这个节点是用来定义每个具体的任务的,多个任务请创建多个job节点即可

  • name(必填) 任务名称,同一个group中多个job的name不能相同,若未设置group则所有未设置group的job为同一个分组,如:sampleJob
  • group(选填) 任务所属分组,用于标识任务所属分组,如:sampleGroup
  • description(选填) 任务描述,用于描述任务具体内容,如:Sample job for Quartz Server
  • job-type(必填) 任务类型,任务的具体类型及所属程序集,格式:实现了IJob接口的包含完整命名空间的类名,程序集名称,如:Quartz.Server.SampleJob, Quartz.Server
  • durable(选填) 具体作用不知,官方示例中默认为true,如:true
  • recover(选填) 具体作用不知,官方示例中默认为false,如:false
2、trigger 任务触发器

用于定义使用何种方式出发任务(job),同一个job可以定义多个trigger ,多个trigger 各自独立的执行调度,每个trigger 中必须且只能定义一种触发器类型(calendar-interval、simple、cron)

calendar-interval 一种触发器类型,使用较少,此处略过
simple 简单任务的触发器,可以调度用于重复执行的任务

  • name(必填) 触发器名称,同一个分组中的名称必须不同
  • group(选填) 触发器组
  • description(选填) 触发器描述
  • job-name(必填) 要调度的任务名称,该job-name必须和对应job节点中的name完全相同
  • job-group(选填) 调度任务(job)所属分组,该值必须和job中的group完全相同
  • start-time(选填) 任务开始执行时间utc时间,北京时间需要+08:00,如:2012-04-01T08:00:00+08:00表示北京时间2012年4月1日上午8:00开始执行,注意服务启动或重启时都会检测此属性,若没有设置此属性或者start-time设置的时间比当前时间较早,则服务启动后会立即执行一次调度,若设置的时间比当前时间晚,服务会等到设置时间相同后才会第一次执行任务,一般若无特殊需要请不要设置此属性
  • repeat-count(必填) 任务执行次数,如:-1表示无限次执行,10表示执行10次
  • repeat-interval(必填) 任务触发间隔(毫秒),如:10000 每10秒执行一次

cron复杂任务触发器--使用cron表达式定制任务调度(强烈推荐)

  • name(必填) 触发器名称,同一个分组中的名称必须不同
  • group(选填) 触发器组d
  • escription(选填) 触发器描述
  • job-name(必填) 要调度的任务名称,该job-name必须和对应job节点中的name完全相同
  • job-group(选填) 调度任务(job)所属分组,该值必须和job中的group完全相同
  • start-time(选填) 任务开始执行时间utc时间,北京时间需要+08:00,如:2012-04-01T08:00:00+08:00表示北京时间2012年4月1日上午8:00开始执行,注意服务启动或重启时都会检测此属性,若没有设置此属性,服务会根据cron-expression的设置执行任务调度;若start-time设置的时间比当前时间较早,则服务启动后会忽略掉cron-expression设置,立即执行一次调度,之后再根据cron-expression执行任务调度;若设置的时间比当前时间晚,则服务会在到达设置时间相同后才会应用cron-expression,根据规则执行任务调度,一般若无特殊需要请不要设置此属性
  • cron-expression(必填) cron表达式,如:0/10 * * * * ?每10秒执行一次
3、Quartz的cron表达式

官方英文介绍地址:http://www.quartz-scheduler.net/documentation/quartz-2.x/tutorial/crontrigger.html
Cron表达式在线生成器:http://cron.qqe2.com/

cron expressions 整体上还是非常容易理解的,只有一点需要注意:"?"号的用法,看下文可以知道“?”可以用在 day of month 和 day of week中,他主要是为了解决如下场景,如:每月的1号的每小时的31分钟,正确的表达式是:* 31 * 1 * ?,而不能是:* 31 * 1 * *,因为这样代表每周的任意一天。

由7段构成:秒 分 时 日 月 星期 年(可选)

  • "-" :表示范围 MON-WED表示星期一到星期三
  • "," :表示列举 MON,WEB表示星期一和星期三
  • "*" :表是“每”,每月,每天,每周,每年等
  • "/" :表示增量:0/15(处于分钟段里面) 每15分钟,在0分以后开始,3/20 每20分钟,从3分钟以后开始
  • "?" :只能出现在日,星期段里面,表示不指定具体的值
  • "L" :只能出现在日,星期段里面,是Last的缩写,一个月的最后一天,一个星期的最后一天(星期六)
  • "W" :表示工作日,距离给定值最近的工作日
  • "#" :表示一个月的第几个星期几,例如:"6#3"表示每个月的第三个星期五(1=SUN...6=FRI,7=SAT)
九、其他参考资料

1、 Asp.Net Core 使用Quartz基于界面画接口管理做定时任务(里面封装了EF的CRUD方法值得参考)
2、.net core获取appsettings CustomSettings
3、Nlog配置实例 彩色Console target
4、Cron表达式的详细用法
5、Cron表达式在线生成器
6、 Asp.Net Core2.0 基于QuartzNet任务管理系统

你可能感兴趣的:(详解如何使用Quartz.NET和Topshelf做任务调度)