概述
基于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