概述
基於Quartz.NET+TopSelf 實現定時服務,支持Job持久化和集羣,異常重啓
同時多太服務器安裝服務,單位時間內,只會有一臺正在執行的服務,如果把正在執行的那臺服務關掉,另外一臺將會開始執行任務(同一臺機器啓動兩個實例,也會有這樣的效果,但是必須保證數據庫Mysql是同一個地方的服務器)
參考
官方學習文檔:http://www.quartz-scheduler.net/documentation/index.html
使用實例介紹:https://www.quartz-scheduler.net/documentation/quartz-3.x/quick-start.html
Demo下載
- CSDN下載:https://download.csdn.net/download/qq_27559331/12272547
- My Service.Job Demo:https://github.com/alanjohn0915/Service.Job
另有Asp.Net Core版:https://blog.csdn.net/qq_27559331/article/details/105729256
關於Quartz.NET和TopSelf介紹和使用我就不在這裏一一介紹了
快速搭建
第一步:安裝
新建一個QuartzDemo項目後,安裝下面的程序包
- Install-Package Topshelf
- Install-Package Topshelf.Log4Net
- Install-Package Quartz
- Install-Package Quartz.Jobs
- Install-Package Quartz.Plugins
- Install-Package Quartz.Serialization.Json
- Install-Package MySql.Data //這裏使用的是MySql作爲Job持久化,所以需要添加MySql的驅動
第二步:實現IJob
Job.cs 實現IJob,在Execute方法裏編寫要處理的業務邏輯,系統就會按照Quartz的配置,定時處理。
public class RegularJob : IJob
{
private readonly ILog _logger = LogManager.GetLogger(typeof(RegularJob));
public async Task Execute(IJobExecutionContext context)
{
try
{
_logger.Info($"Message:{nameof(RegularJob)} Starting,DateTime:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
await new RegularProcessJob().RunAsync(context);
_logger.Info($"Message:{nameof(RegularJob)} Complated,DateTime:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
}
catch (Exception e)
{
_logger.Error($"Message:Error,Reexecution will be delayed by {ServiceRunner.RestartTime}minutes", e);
//轉換爲可調度異常
var jobException = new JobExecutionException(e);
//延遲指定時間
await Task.Delay(TimeSpan.FromMinutes(ServiceRunner.RestartTime), context.CancellationToken);
// 立即重新執行
jobException.RefireImmediately = true;
throw jobException;
}
}
}
第三步:使用Topshelf調度任務
ServiceRunner.cs
public class ServiceRunner : ServiceControl, ServiceSuspend
{
//Delayed start time
public static int RestartTime;
private readonly IScheduler _scheduler;
private readonly ILog _logger = LogManager.GetLogger(typeof(ServiceRunner));
public ServiceRunner()
{
try
{
RestartTime = ConfigurationManager.AppSettings["RestartTime"].Trim(' ').StringToInt32(1);
if (RestartTime < 1) RestartTime = 1;
var properties = GetProperties();
var stdSchedulerFactory = new StdSchedulerFactory(properties);
_scheduler = stdSchedulerFactory.GetScheduler().Result;
}
catch (Exception e)
{
_logger.Error($"Message:ServiceRunner initialization failure,Error Message:{e.Message},DateTime:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}", e);
throw;
}
}
/// <summary>
/// Read the Quartz.Net configuration from the config file
/// </summary>
/// <returns></returns>
public NameValueCollection GetProperties()
{
try
{
var quartzFile = ConfigurationManager.AppSettings["QuartzFile"].Trim(' ');
var requestedFile = QuartzEnvironment.GetEnvironmentVariable(quartzFile);
var propFileName = !string.IsNullOrWhiteSpace(requestedFile) ? requestedFile : $"~/{quartzFile}";
propFileName = FileUtil.ResolveFile(propFileName);
var propertiesParser = PropertiesParser.ReadFromFileResource(propFileName);
var properties = propertiesParser.UnderlyingProperties;
return properties;
}
catch (Exception e)
{
_logger.Error($"Message:ServiceRunner Reading the Quartz config file failed,Error Message:{e.Message},DateTime:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}", e);
}
return new NameValueCollection();
}
public bool Start(HostControl hostControl)
{
try
{
_scheduler.Start();
}
catch (Exception e)
{
_logger.Error($"Message:ServiceRunner start failure,Error Message: {e.Message},DateTime:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}", e);
}
_logger.Info($"Message:ServiceRunner start success,DateTime:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
return true;
}
public bool Stop(HostControl hostControl)
{
try
{
_scheduler.Shutdown(false);
}
catch (Exception e)
{
_logger.Error($"Message:ServiceRunner stop failure:{e.Message},DateTime:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}", e);
}
_logger.Info($"Message:ServiceRunner stop success,DateTime:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
return true;
}
public bool Continue(HostControl hostControl)
{
_scheduler.ResumeAll();
return true;
}
public bool Pause(HostControl hostControl)
{
_scheduler.PauseAll();
return true;
}
}
第四步:程序入口
class Program
{
static void Main(string[] args)
{
var logger = LogManager.GetLogger(typeof(Program));
log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"));
try
{
HostFactory.Run(x => {
x.UseLog4Net();
x.SetServiceName("Service.Job");
x.SetDisplayName("Service.Job");
x.SetDescription("Service.Job後端任務處理");
x.Service<ServiceRunner>();
x.EnablePauseAndContinue();
});
}
catch (Exception e)
{
logger.Error($"Message:Start failure,DateTime:{DateTime.Now.ToString("yyyy - MM - dd HH: mm:ss")}", e);
}
}
}
第五步:配置App.config、quartz.config、quartz_jobs.xml、log4net.config、install.bat、uninstall.bat
說明:這六個文件,分別選中→右鍵屬性→複製到輸入目錄設爲:始終複製
第六步:配置文件
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
<!--Delayed start time-->
<add key="RestartTime" value="10" />
<!--Quartz Profile address-->
<add key="QuartzFile" value="quartz.config" />
</appSettings>
</configuration>
quartz.config
# You can configure your scheduler in either <quartz> configuration section
# or in quartz properties file
# Configuration section has precedence
# configure thread pool info
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
#配置集羣
#設置存儲類型
quartz.jobStore.type = Quartz.Impl.AdoJobStore.JobStoreTX, Quartz
#驅動類型
quartz.jobStore.driverDelegateType = Quartz.Impl.AdoJobStore.StdAdoDelegate, Quartz
#使用表前綴配置AdoJobStore
quartz.jobStore.tablePrefix = QRTZ_
#數據源名稱,於 quartz.dataSource 的屬性名一樣
quartz.jobStore.dataSource = db_ServiceJob
#數據連接字符串
quartz.dataSource.db_ServiceJob.connectionString = Server=127.0.0.1; Database=db_ServiceJob; User ID = root; Password=123456;port=3306;SslMode = none;CharSet=utf8;pooling=true;Min Pool Size=1;Max Pool Size=300;Connection Timeout=60;
#數據庫類型
quartz.dataSource.db_ServiceJob.provider = MySql
#JobDataMaps 中的值只能是字符串,具體可以看官方推薦這樣設置的原因
quartz.jobStore.useProperties = true
#數據存儲序列號方式
quartz.serializer.type = json
#是否是集羣模式
quartz.jobStore.clustered = true
#集羣的名稱
quartz.scheduler.instanceName = ServiceJob
#自動生成唯一的instanceId
quartz.scheduler.instanceId = AUTO
quartz_jobs.xml
<?xml version="1.0" encoding="UTF-8"?>
<job-scheduling-data xmlns="http://quartznet.sourceforge.net/JobSchedulingData" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0">
<processing-directives>
<overwrite-existing-data>true</overwrite-existing-data>
</processing-directives>
<schedule>
<!--RegularJob測試 任務配置-->
<!--job 任務-->
<job>
<!--name(必填) 任務名稱,同一個group中多個job的name不能相同,若未設置group則所有未設置group的job爲同一個分組,如:<name>sampleJob</name>-->
<name>RegularJob</name>
<!--group(選填) 任務所屬分組,用於標識任務所屬分組,如:<group>sampleGroup</group>-->
<group>Regular</group>
<!--description(選填) 任務描述,用於描述任務具體內容,如:<description>Sample job for Quartz Server</description>-->
<description>RegularJob測試</description>
<!--job-type(必填) 任務類型,任務的具體類型及所屬程序集,格式:實現了IJob接口的包含完整命名空間的類名,程序集名稱,如:<job-type>Quartz.Server.SampleJob, Quartz.Server</job-type>-->
<job-type>Service.Job.Jobs.RegularJob,Service.Job</job-type>
<!--durable(選填) 具體作用不知,官方示例中默認爲true,如:<durable>true</durable>-->
<durable>true</durable>
<!--recover(選填) 具體作用不知,官方示例中默認爲false,如:<recover>false</recover>-->
<recover>false</recover>
</job>
<!--trigger 任務觸發器-->
<!--用於定義使用何種方式出發任務(job),同一個job可以定義多個trigger ,多個trigger 各自獨立的執行調度,每個trigger 中必須且只能定義一種觸發器類型(calendar-interval、simple、cron)-->
<trigger>
<cron>
<!--name(必填) 觸發器名稱,同一個分組中的名稱必須不同-->
<name>RegularJobTrigger</name>
<!--group(選填) 觸發器組-->
<group>Regular</group>
<!--description(選填) 觸發器描述-->
<description>Ttrigger測試</description>
<!--job-name(必填) 要調度的任務名稱,該job-name必須和對應job節點中的name完全相同-->
<job-name>RegularJob</job-name>
<!--job-group(選填) 調度任務(job)所屬分組,該值必須和job中的group完全相同-->
<job-group>Regular</job-group>
<!--start-time(選填) 任務開始執行時間utc時間,北京時間需要+08:00,如:<start-time>2012-04-01T08:00:00+08:00</start-time>表示北京時間2012年4月1日上午8:00開始執行,注意服務啓動或重啓時都會檢測此屬性,若沒有設置此屬性或者start-time設置的時間比當前時間較早,則服務啓動後會立即執行一次調度,若設置的時間比當前時間晚,服務會等到設置時間相同後纔會第一次執行任務,一般若無特殊需要請不要設置此屬性-->
<start-time>2020-01-01T00:00:00+08:00</start-time>
<!--cron-expression(必填) cron表達式,如:<cron-expression>0/10 * * * * ?</cron-expression>每10秒執行一次-->
<cron-expression>0/10 * * * * ?</cron-expression>
</cron>
</trigger>
</schedule>
</job-scheduling-data>
log4net.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<!--日誌路徑-->
<param name= "File" value= "D:\App_Log\servicelog\"/>
<!--是否是向文件中追加日誌-->
<param name= "AppendToFile" value= "true"/>
<!--log保留天數-->
<param name= "MaxSizeRollBackups" value= "30"/>
<!--日誌文件名是否是固定不變的-->
<param name= "StaticLogFileName" value= "false"/>
<!--日誌文件名格式爲:2008-08-31.log-->
<param name= "DatePattern" value= "yyyy-MM-dd".read.log""/>
<!--日誌根據日期滾動-->
<param name= "RollingStyle" value= "Date"/>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n %loggername" />
</layout>
</appender>
<!-- 控制檯前臺顯示日誌 -->
<appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
<mapping>
<level value="ERROR" />
<foreColor value="Red, HighIntensity" />
</mapping>
<mapping>
<level value="Info" />
<foreColor value="Green" />
</mapping>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%n%date{HH:mm:ss,fff} [%-5level] %m" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="Info" />
<param name="LevelMax" value="Fatal" />
</filter>
</appender>
<root>
<!--(高) OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL (低) -->
<level value="all" />
<appender-ref ref="ColoredConsoleAppender"/>
<appender-ref ref="RollingLogFileAppender"/>
</root>
</log4net>
</configuration>
第七步:安裝成windows服務
打開Service.Job\src\Service.Job\bin\Debug 或者Service.Job\src\Service.Job\bin\Release(具體看你選擇的是那種發佈)
cmd右鍵以管理員身份運行
>cd C:\Users\Administration\Desktop\Service.Job\Service.Job\src\Service.Job\bin\Debug
>sc delete Service.Job
>Service.Job install
>Service.Job start
安裝完成之後就可以在服務中找到你寫的服務了
卸載服務
>cd C:\Users\Administration\Desktop\Service.Job\Service.Job\src\Service.Job\bin\Debug
>Service.Job uninstall