.Net Core 2.0 的 ConsoleApp 搭建 Quartz(xml配置)windows服务

时间:2020-11-29 03:01:44

零、创建一个.Net Core 2.0 的ConsoleApp 应用,建完就是这个样子了。

添加Log4Net 的引用,(不想看可以不看,个人习惯)
Install-Package log4net
添加Config文件夹
往文件夹里面添加Log4net.xml(别忘记了设置Copy always)
添加Log4NetConfig.cs文件
往里面写几行代码

 /// <summary>
/// log4net拓展
/// </summary>
public sealed class Log4netConfig
{
/// <summary>
/// 配置默认数据
/// </summary>
public static void DefalutConfig()
{
var defalutResposity = LogManager.GetRepository(Assembly.GetCallingAssembly());
var path = Path.Combine(Directory.GetCurrentDirectory(), "Config", "Log4net.xml");
XmlConfigurator.Configure(defalutResposity, new FileInfo(path));
}
}

Log4netConfig

在Main函数加下面几行代码

 Environment.CurrentDirectory = AppContext.BaseDirectory;
Log4NetConfig.DefalutConfig();
var logger = LogManager.GetLogger(typeof(Program));
logger.Info("服务开始");

Main

得到的差不多就是这样了

.Net Core 2.0 的 ConsoleApp 搭建 Quartz(xml配置)windows服务

运行下,可以看到日志基本就没错了。

一、windows服务的搭建

大概或许是看下了https://github.com/aspnet/Hosting/tree/dev/src/Microsoft.AspNetCore.Hosting,随便乱写的

1.引用
Install-Package System.ServiceProcess.ServiceController
Install-Package Install-Package System.Configuration.ConfigurationManager

2.添加appSettings.config
在Config文件夹下添加appSettings.config
添加内容

<appSettings>
  <!--服务名称-->
  <add key="ServiceName" value="MyTestService"/>
</appSettings>

3.添加HostService.cs

然后写上如下代码

  /// <summary>
/// 服务
/// </summary>
public class HostService : ServiceBase
{
private ILog Log = LogManager.GetLogger(typeof(HostService)); /// <summary>
/// Creates an instance of <c>WebHostService</c> which hosts the specified web application.
/// </summary>
/// <param name="host">The configured web host containing the web application to host in the Windows service.</param>
public HostService()
{
} public void Start()
{
Log.Info($"{base.ServiceName}服务开启");
OnStart(null);
} protected sealed override void OnStart(string[] args)
{
OnStarting(args);
//dosomthing
OnStarted();
} protected sealed override void OnStop()
{
Log.Info($"{base.ServiceName}服务关闭");
OnStopping();
try
{
}
finally
{
OnStopped();
}
} /// <summary>
/// Executes before ASP.NET Core starts.
/// </summary>
/// <param name="args">The command line arguments passed to the service.</param>
protected virtual void OnStarting(string[] args) { } /// <summary>
/// Executes after ASP.NET Core starts.
/// </summary>
protected virtual void OnStarted() { } /// <summary>
/// Executes before ASP.NET Core shuts down.
/// </summary>
protected virtual void OnStopping() { } /// <summary>
/// Executes after ASP.NET Core shuts down.
/// </summary>
protected virtual void OnStopped() { }
}

HostService

4. Main 改为如下代码

 var serviceName = ConfigurationManager.AppSettings["ServiceName"];
var hostService = new HostService { ServiceName = serviceName };
logger.Info("服务开始");
#if DEBUG
//服务名称赋值
Console.WriteLine($"{serviceName}服务开启...");
hostService.Start(); Console.ReadKey(true);
hostService.Stop();
Console.WriteLine($"{serviceName}服务停止");
#else
logger.Info($"{serviceName}服务开启...");
var servicesToRun = new ServiceBase[] { hostService };
ServiceBase.Run(servicesToRun);
#endif
Console.ReadLine();

Main

这个时候,运行,服务就可以启动了。

大概就是这么个效果

.Net Core 2.0 的 ConsoleApp 搭建 Quartz(xml配置)windows服务

二、quart的使用

1.引用
添加引用
Install-Package Quartz
Install-Package Quartz.Plugins

2.添加TestQuartzService .cs 文件,写入以下代码

 public class TestQuartzService : IDisposable
{
private ILog Log = LogManager.GetLogger(typeof(TestQuartzService));
public List<IScheduler> Schedulers = new List<IScheduler>();
public void Start()
{
Log.Info("quartz开启!");
// 从工厂中获取调度程序实例
StdSchedulerFactory factory = new StdSchedulerFactory();
IScheduler scheduler = factory.GetScheduler().Result;
Schedulers.Add(scheduler);
scheduler.Start();
Log.Info("quartz开启完成!");
} public void Stop()
{
Log.Info("quartz关闭!");
foreach (var scheduler in Schedulers)
{
scheduler.Shutdown().GetAwaiter().GetResult();
}
Log.Info("quartz关闭完成!");
} public void Dispose()
{
foreach (var scheduler in Schedulers)
{
if (scheduler.IsStarted)
{
scheduler.Shutdown().GetAwaiter().GetResult();
}
}
}
}

TestQuartzService

3.添加TestJob.cs文件

写入以下代码

 public class TestJob : IJob
{
private ILog Log = LogManager.GetLogger(typeof(TestJob));
public Task Execute(IJobExecutionContext context)
{
Log.Info("测试job启动");
Console.WriteLine("测试job启动");
return Task.CompletedTask;
}
}

TestJob

4.添加 quartz.config

 # You can configure your scheduler in either <quartz> configuration section
# or in quartz properties file
# Configuration section has precedence quartz.scheduler.instanceName = ServerScheduler # configure thread pool info
quartz.threadPool.type = Quartz.Simpl.SimpleThreadPool, Quartz
quartz.threadPool.threadCount =
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.config

5.添加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>
<job>
<name>TestJob</name>
<group>TestJobGroup</group>
<description>测试Job</description>
<job-type>TestQuartzService.TestJob,TestQuartzService</job-type>
<durable>true</durable>
<recover>false</recover>
</job>
<trigger>
<cron>
<name>TestJobJobTrigger</name>
<group>TestJobTriggerGroup</group>
<job-name>TestJob</job-name>
<job-group>TestJobGroup</job-group>
<misfire-instruction>DoNothing</misfire-instruction>
<cron-expression>/ * * * * ?</cron-expression>
</cron>
</trigger>
</schedule>
</job-scheduling-data>

quartz_job

6.HostService.cs改为

 /// <summary>
/// 服务
/// </summary>
public class HostService : ServiceBase
{
private ILog Log = LogManager.GetLogger(typeof(HostService)); private TestQuartzService _testQuartzService;
/// <summary>
/// Creates an instance of <c>WebHostService</c> which hosts the specified web application.
/// </summary>
/// <param name="host">The configured web host containing the web application to host in the Windows service.</param>
public HostService()
{
_testQuartzService = new TestQuartzService();
} public void Start()
{
Log.Info($"{base.ServiceName}服务开启");
OnStart(null);
} protected sealed override void OnStart(string[] args)
{
OnStarting(args);
//dosomthing
_testQuartzService.Start();
OnStarted();
} protected sealed override void OnStop()
{
Log.Info($"{base.ServiceName}服务关闭");
OnStopping();
try
{
_testQuartzService.Stop();
}
finally
{
OnStopped();
}
} /// <summary>
/// Executes before ASP.NET Core starts.
/// </summary>
/// <param name="args">The command line arguments passed to the service.</param>
protected virtual void OnStarting(string[] args) { } /// <summary>
/// Executes after ASP.NET Core starts.
/// </summary>
protected virtual void OnStarted() { } /// <summary>
/// Executes before ASP.NET Core shuts down.
/// </summary>
protected virtual void OnStopping() { } /// <summary>
/// Executes after ASP.NET Core shuts down.
/// </summary>
protected virtual void OnStopped() { }
}

HostService

6.尝试启动

.Net Core 2.0 的 ConsoleApp 搭建 Quartz(xml配置)windows服务

三、安装为windows服务

1.编辑TestQuartzService.csproj
添加 <RuntimeIdentifier>win-x64-corert</RuntimeIdentifier>

.Net Core 2.0 的 ConsoleApp 搭建 Quartz(xml配置)windows服务

2.Main的引用添加(不添加release会报错,因为使用了 var servicesToRun = new ServiceBase[] { hostService };)

using System.ServiceProcess;

3.点击发布

.Net Core 2.0 的 ConsoleApp 搭建 Quartz(xml配置)windows服务

这下就会在 netcoreapp2.0\win-x64-corert 出现

.Net Core 2.0 的 ConsoleApp 搭建 Quartz(xml配置)windows服务

有了这个exe就可以进行第四步了

4.管理员打开CMD
输入以下
sc create TestQuartzService binpath=E:\liuyue\TestQuartzService\TestQuartzService\bin\Release\netcoreapp2.0\win-x64-corert\TestQuartzService.exe

.Net Core 2.0 的 ConsoleApp 搭建 Quartz(xml配置)windows服务

看到

.Net Core 2.0 的 ConsoleApp 搭建 Quartz(xml配置)windows服务

5、打开服务找到

.Net Core 2.0 的 ConsoleApp 搭建 Quartz(xml配置)windows服务

点启动
看到日志有日志不断输出

.Net Core 2.0 的 ConsoleApp 搭建 Quartz(xml配置)windows服务

四、完结

值得注意一点就是,各种config、xml文件,记得copy always。
到这就弄完了。有什么问自己,翻源码去吧