.NET使用quartz+topshelf实现定时执行任务调度服务

一、项目开发

1.新建控制台应用(.NET Framework)

2.配置新项目,自行修改项目名称、位置和框架(建议使用.NET Framework4.5以上版本)

创建好的项目目录如下:

 3.右键引用,点击添加引用(R)...

 4.引用管理器->程序集->框架,添加System.Configuration引用

点击确定,即添加引用到项目中。

5.右键引用,点击管理NuGet程序包(N)...

按照以下顺序添加包:

 

包名

版本

依赖项

Common.Logging.Core

3.3.1

 

Common.Logging

3.3.1

Common.Logging.Core (>= 3.3.1)

Quartz

2.6.2

Common.Logging (>= 3.3.1)

log4net

2.0.5

 

Topshelf

3.3.1

 

Topshelf.Log4Net

3.3.1

Topshelf (>= 3.3.1)

log4net (>= 2.0.5)

添加完毕后如图:

6.添加配置文件

添加配置文件步骤如下:

(1)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= "Log\"/>
			<!--是否是向文件中追加日志-->
			<param name= "AppendToFile" value= "true"/>
			<!--log保留天数-->
			<param name= "MaxSizeRollBackups" value= "10"/>
			<!--日志文件名是否是固定不变的-->
			<param name= "StaticLogFileName" value= "false"/>
			<!--日志文件名格式为:2008-08-31.log-->
			<param name= "DatePattern" value= "yyyy-MM-dd".log""/>
			<!--日志根据日期滚动-->
			<param name= "RollingStyle" value= "Date"/>
			<layout type="log4net.Layout.PatternLayout">
				<param name="ConversionPattern" value="%date{HH:mm:ss,fff} %-5p-%m%n" />
			</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>

(2)quartz.config

内容如下:

# You can configure your scheduler in either <quartz> 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 = 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
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

(3)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>
		<!--AlarmJob任务配置-->
		<job>
			<name>AlarmJob</name>
			<group>Alarm</group>
			<description>Alarm任务调度</description>
			<job-type>AlarmService.QuartzJobs.AlarmJob,AlarmService</job-type>
			<durable>true</durable>
			<recover>false</recover>
		</job>
		<trigger>
			<cron>
				<name>AlarmJobTrigger</name>
				<group>Alarm</group>
				<job-name>AlarmJob</job-name>
				<job-group>Alarm</job-group>
				<!--从start-time起,每天15:50执行一次-->
				<start-time>2023-09-07T15:50:00+08:00</start-time>
				<cron-expression>0 50 15 * * ?</cron-expression>
			</cron>
		</trigger>
	</schedule>
</job-scheduling-data>

选中三个文件->右键->属性,复制到输出目录:如果较新则复制

7.添加服务运行类:ServiceRunner

namespace AlarmService
{
    public class ServiceRunner : Topshelf.ServiceControl, Topshelf.ServiceSuspend
    {
        private readonly Quartz.IScheduler scheduler;
        public ServiceRunner()
        {
            scheduler = Quartz.Impl.StdSchedulerFactory.GetDefaultScheduler();
        }
        public bool Start(Topshelf.HostControl hostControl)
        {
            scheduler.Start();
            return true;
        }
        public bool Stop(Topshelf.HostControl hostControl)
        {
            scheduler.Shutdown(false);
            return true;
        }
        public bool Continue(Topshelf.HostControl hostControl)
        {
            scheduler.ResumeAll();
            return true;
        }
        public bool Pause(Topshelf.HostControl hostControl)
        {
            scheduler.PauseAll();
            return true;
        }
    }
}

8.Program.cs中增加代码:

using System;
using Topshelf;
namespace AlarmService
{
    class Program
    {
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"));
            Topshelf.HostFactory.Run(x =>
            {
                x.UseLog4Net();
                x.Service<ServiceRunner>();
                x.RunAsLocalSystem();
                x.SetDescription("Quartz+TopShelf implements a Windows service that to achieve timing task scheduling.");
                x.SetDisplayName("Alarm");
                x.SetServiceName("AlarmService");
                x.EnablePauseAndContinue();
            });
        }
    }
}

9.增加帮助类:CommonHelper

namespace AlarmService
{
    public class CommonHelper
    {
        public static readonly log4net.ILog AppLogger = log4net.LogManager.GetLogger("AppLogger");
    }
}

10.添加文件夹:QuartzJobs

在QuartzJobs文件夹下新建类:AlarmJob 

该类继承Quartz.IJob,实现接口,如下图:

AlarmJob类完整代码如下:

namespace AlarmService.QuartzJobs
{
    public sealed class AlarmJob : Quartz.IJob
    {
        public void Execute(Quartz.IJobExecutionContext context)
        {
            CommonHelper.AppLogger.InfoFormat("AlarmJob开始...");
       //TODO 业务逻辑 CommonHelper.AppLogger.InfoFormat("AlarmJob结束"); } } }

二、测试

在项目的bin/Debug下新建Log文件夹。F5启动项目

进入断点

控制台显示日志:

Log文件夹下的日志:

三、安装服务

1.找一台服务器,把项目目录下bin\Debug的文件夹复制到服务器某个磁盘下,windows键输入cmd,显示命令提示符,右键命令提示符,以管理员身份运行,在窗体中输入“cd C:\xxx”,(xxx为AlarmService.exe所在的文件夹),回车后继续输入“AlarmService.exe install”,显示已完成事务处理安装。

2.win+R键打开运行,输入“services.msc”,点击确定,打开服务,找到AlarmService,右键“启动(S)”即可。

3.在xxx\Log下即可看到相应的日志。

 

源码网盘地址:
链接:https://pan.baidu.com/s/1m62Pu44KypipGVBukDhNrA
提取码:08g2

posted @ 2023-09-13 17:37  不懂01的ITer  阅读(1584)  评论(3编辑  收藏  举报