.NET使用quartz+topshelf實現定時執行任務排程服務

2023-09-13 18:00:12

一、專案開發

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