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


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

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

     1 /// <summary>
     2     /// log4net拓展
     3     /// </summary>
     4     public sealed class Log4netConfig
     5     {
     6         /// <summary>
     7         /// 配置默认数据
     8         /// </summary>
     9         public static void DefalutConfig()
    10         {
    11             var defalutResposity = LogManager.GetRepository(Assembly.GetCallingAssembly());
    12             var path = Path.Combine(Directory.GetCurrentDirectory(), "Config", "Log4net.xml");
    13             XmlConfigurator.Configure(defalutResposity, new FileInfo(path));
    14         }
    15     }
    Log4netConfig

    在Main函数加下面几行代码

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

    得到的差不多就是这样了

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

    一、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

    然后写上如下代码

     1  /// <summary>
     2     /// 服务
     3     /// </summary>
     4     public class HostService : ServiceBase
     5     {
     6         private ILog Log = LogManager.GetLogger(typeof(HostService)); 
     7 
     8         /// <summary>
     9         /// Creates an instance of <c>WebHostService</c> which hosts the specified web application.
    10         /// </summary>
    11         /// <param name="host">The configured web host containing the web application to host in the Windows service.</param>
    12         public HostService()
    13         { 
    14         }
    15 
    16         public void Start()
    17         {
    18             Log.Info($"{base.ServiceName}服务开启");
    19             OnStart(null);
    20         }
    21 
    22         protected sealed override void OnStart(string[] args)
    23         {
    24             OnStarting(args);
    25             //dosomthing 
    26             OnStarted();
    27         }
    28 
    29         protected sealed override void OnStop()
    30         {
    31             Log.Info($"{base.ServiceName}服务关闭");
    32             OnStopping();
    33             try
    34             { 
    35             }
    36             finally
    37             {
    38                 OnStopped();
    39             }
    40         }
    41 
    42         /// <summary>
    43         /// Executes before ASP.NET Core starts.
    44         /// </summary>
    45         /// <param name="args">The command line arguments passed to the service.</param>
    46         protected virtual void OnStarting(string[] args) { }
    47 
    48         /// <summary>
    49         /// Executes after ASP.NET Core starts.
    50         /// </summary>
    51         protected virtual void OnStarted() { }
    52 
    53         /// <summary>
    54         /// Executes before ASP.NET Core shuts down.
    55         /// </summary>
    56         protected virtual void OnStopping() { }
    57 
    58         /// <summary>
    59         /// Executes after ASP.NET Core shuts down.
    60         /// </summary>
    61         protected virtual void OnStopped() { }
    62     }
    HostService

    4. Main 改为如下代码

     1 var serviceName = ConfigurationManager.AppSettings["ServiceName"];
     2             var hostService = new HostService { ServiceName = serviceName };
     3             logger.Info("服务开始");
     4 #if DEBUG
     5             //服务名称赋值
     6             Console.WriteLine($"{serviceName}服务开启...");
     7             hostService.Start();
     8 
     9             Console.ReadKey(true);
    10             hostService.Stop();
    11             Console.WriteLine($"{serviceName}服务停止");
    12 #else
    13             logger.Info($"{serviceName}服务开启...");
    14             var servicesToRun = new ServiceBase[] { hostService };
    15             ServiceBase.Run(servicesToRun);
    16 #endif 
    17             Console.ReadLine();
    Main

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

    大概就是这么个效果



    二、quart的使用


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


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

     1 public class TestQuartzService : IDisposable
     2     {
     3         private ILog Log = LogManager.GetLogger(typeof(TestQuartzService));
     4         public List<IScheduler> Schedulers = new List<IScheduler>();
     5         public void Start()
     6         {
     7             Log.Info("quartz开启!");
     8             // 从工厂中获取调度程序实例
     9             StdSchedulerFactory factory = new StdSchedulerFactory();
    10             IScheduler scheduler = factory.GetScheduler().Result;
    11             Schedulers.Add(scheduler);
    12             scheduler.Start();
    13             Log.Info("quartz开启完成!");
    14         }
    15 
    16         public void Stop()
    17         {
    18             Log.Info("quartz关闭!");
    19             foreach (var scheduler in Schedulers)
    20             {
    21                 scheduler.Shutdown().GetAwaiter().GetResult();
    22             }
    23             Log.Info("quartz关闭完成!");
    24         }
    25 
    26         public void Dispose()
    27         {
    28             foreach (var scheduler in Schedulers)
    29             {
    30                 if (scheduler.IsStarted)
    31                 {
    32                     scheduler.Shutdown().GetAwaiter().GetResult();
    33                 }
    34             }
    35         }
    36     }
    TestQuartzService

    3.添加TestJob.cs文件

    写入以下代码

     1 public class TestJob : IJob
     2     {
     3         private ILog Log = LogManager.GetLogger(typeof(TestJob));
     4         public Task Execute(IJobExecutionContext context)
     5         {
     6             Log.Info("测试job启动");
     7             Console.WriteLine("测试job启动");
     8             return Task.CompletedTask;
     9         }
    10     }
    TestJob

    4.添加 quartz.config

     1 # You can configure your scheduler in either <quartz> configuration section
     2 # or in quartz properties file
     3 # Configuration section has precedence
     4 
     5 quartz.scheduler.instanceName = ServerScheduler
     6 
     7 # configure thread pool info
     8 quartz.threadPool.type = Quartz.Simpl.SimpleThreadPool, Quartz
     9 quartz.threadPool.threadCount = 10
    10 quartz.threadPool.threadPriority = Normal
    11 
    12 # job initialization plugin handles our xml reading, without it defaults are used
    13 quartz.plugin.xml.type = Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz.Plugins
    14 quartz.plugin.xml.fileNames = ~/quartz_jobs.xml
    quartz.config

    5.添加quartz_jobs.xml 

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <job-scheduling-data xmlns="http://quartznet.sourceforge.net/JobSchedulingData" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0">
     3   <processing-directives>
     4     <overwrite-existing-data>true</overwrite-existing-data>
     5   </processing-directives>
     6   <schedule>
     7     <job>
     8       <name>TestJob</name>
     9       <group>TestJobGroup</group>
    10       <description>测试Job</description>
    11       <job-type>TestQuartzService.TestJob,TestQuartzService</job-type>
    12       <durable>true</durable>
    13       <recover>false</recover>
    14     </job>
    15     <trigger>
    16       <cron>
    17         <name>TestJobJobTrigger</name>
    18         <group>TestJobTriggerGroup</group>
    19         <job-name>TestJob</job-name>
    20         <job-group>TestJobGroup</job-group>
    21         <misfire-instruction>DoNothing</misfire-instruction>
    22         <cron-expression>0/3 * * * * ?</cron-expression>
    23       </cron>
    24     </trigger>
    25   </schedule>
    26 </job-scheduling-data>
    quartz_job

    6.HostService.cs改为

     1 /// <summary>
     2     /// 服务
     3     /// </summary>
     4     public class HostService : ServiceBase
     5     {
     6         private ILog Log = LogManager.GetLogger(typeof(HostService));
     7 
     8         private TestQuartzService _testQuartzService;
     9         /// <summary>
    10         /// Creates an instance of <c>WebHostService</c> which hosts the specified web application.
    11         /// </summary>
    12         /// <param name="host">The configured web host containing the web application to host in the Windows service.</param>
    13         public HostService()
    14         {
    15             _testQuartzService = new TestQuartzService();
    16         }
    17 
    18         public void Start()
    19         {
    20             Log.Info($"{base.ServiceName}服务开启");
    21             OnStart(null);
    22         }
    23 
    24         protected sealed override void OnStart(string[] args)
    25         {
    26             OnStarting(args);
    27             //dosomthing 
    28              _testQuartzService.Start();
    29             OnStarted();
    30         }
    31 
    32         protected sealed override void OnStop()
    33         {
    34             Log.Info($"{base.ServiceName}服务关闭");
    35             OnStopping();
    36             try
    37             {
    38                 _testQuartzService.Stop();
    39             }
    40             finally
    41             {
    42                 OnStopped();
    43             }
    44         }
    45 
    46         /// <summary>
    47         /// Executes before ASP.NET Core starts.
    48         /// </summary>
    49         /// <param name="args">The command line arguments passed to the service.</param>
    50         protected virtual void OnStarting(string[] args) { }
    51 
    52         /// <summary>
    53         /// Executes after ASP.NET Core starts.
    54         /// </summary>
    55         protected virtual void OnStarted() { }
    56 
    57         /// <summary>
    58         /// Executes before ASP.NET Core shuts down.
    59         /// </summary>
    60         protected virtual void OnStopping() { }
    61 
    62         /// <summary>
    63         /// Executes after ASP.NET Core shuts down.
    64         /// </summary>
    65         protected virtual void OnStopped() { }
    66     }
    HostService

    6.尝试启动

    三、安装为windows服务


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

     

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

    using System.ServiceProcess;

    3.点击发布

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

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

    4.管理员打开CMD
    输入以下
    sc create TestQuartzService binpath=E:liuyueTestQuartzServiceTestQuartzServiceinRelease etcoreapp2.0win-x64-corertTestQuartzService.exe

    看到

     

    5、打开服务找到

     

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

    四、完结


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

  • 相关阅读:
    家里蹲大学数学杂志期刊模式目录
    [历朝通俗演义-蔡东藩-前汉]第008回 葬始皇骊山成巨冢 戮宗室豻狱构奇冤
    [历朝通俗演义-蔡东藩-前汉]第007回 寻生路徐市垦荒 从逆谋李斯矫诏
    [历朝通俗演义-蔡东藩-前汉]第006回 阬深谷诸儒毙命 得原璧暴主惊心
    [历朝通俗演义-蔡东藩-前汉]第005回 信佞臣尽毁诗书 筑阿房大兴土木
    [历朝通俗演义-蔡东藩-前汉]第004回 误椎击逃生遇异士 见图谶遣将造长城
    [历朝通俗演义-蔡东藩-前汉]第003回 封泰岱下山避雨 过湘江中渡惊风
    [历朝通俗演义-蔡东藩]
    [历朝通俗演义-蔡东藩-前汉]第002回 诛假父纳言迎母 称皇帝立法愚民
    [历朝通俗演义-蔡东藩-前汉]第001回 移花接木计献美姬 用李代桃欢承淫后
  • 原文地址:https://www.cnblogs.com/Cowait/p/9121205.html
Copyright © 2020-2023  润新知