零、创建一个.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

得到的差不多就是这样了

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

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

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

大概就是这么个效果

二、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.尝试启动

三、安装为windows服务

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

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

using System.ServiceProcess;

3.点击发布

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

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

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

看到

5、打开服务找到

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

四、完结

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

.Net Core 2.0 的 ConsoleApp 搭建 Quartz(xml配置)windows服务的更多相关文章

  1. Quartz+TopShelf实现Windows服务作业调度

    Quartz:首先我贴出来了两段代码(下方),可以看出,首先会根据配置文件(quartz.config),包装出一个Quartz.Core.QuartzScheduler instance,这是一个调 ...

  2. 基于.net core 2.0+mysql+AceAdmin搭建一套快速开发框架

    前言 .net core已经出来一段时间了,相信大家对.net core的概念已经很清楚了,这里就不再赘述.笔者目前也用.net core做过一些项目,并且将以前framework下的一些经验移植到了 ...

  3. win10下ASP.NET Core 2.0部署环境搭建(转)

    此文用于记录在win10环境下,新建的Asp.net Core 2.0 Web应用项目如何运行在IIS上 一.运行环境 操作系统: Window10 家庭中文版 版本 10.0.15063 版本 15 ...

  4. Quartz.Net在windows服务中的使用

    写在前面 这几天在弄一个项目,需要定时抓取一些数据,当时也想直接用timer算了.因为之前也弄过这样的项目,但是一想,已经用过了,再去使用同一种思路,未免太乏味了.就换了一种新玩法.这里将之前看到的一 ...

  5. 使用 Topshelf 结合 Quartz.NET 创建 Windows 服务

    Ø  前言 之前一篇文章已经介绍了,如何使用 Topshelf 创建 Windows 服务.当时提到还缺少一个任务调度框架,就是 Quartz.NET.而本文就展开对 Quartz.NET 的研究,以 ...

  6. 利用Topshelf把.NET Core Generic Host管理的应用程序部署为Windows服务

    背景 2019第一篇文章. 此文源于前公司在迁移项目到.NET Core的过程中,希望使用Generic Host来管理定时任务程序时,没法部署到Windows服务的问题,而且官方也没给出解决方案,只 ...

  7. Quartz和TopShelf Windows服务作业调度

    上一次写了一遍关于Quartz作业调度的文章 Quartz.NET 作业调度使用 现在使用TopShelf和Quartz实现windows服务作业调度 TopShelf版本4.0 Quartz版本3. ...

  8. Quartz.net创建windows服务

    序言 安装服务 sc create XXService binpath= "XXService.exe" start= auto sc description XXService ...

  9. servlet3.0以后可以不用web.xml配置了

    AbstractDispatcherServletInitializer 注意:删除了web.xml会报错,web.xml is missing and <failOnMissingWebXml ...

随机推荐

  1. Solr中Facet用法和Group用法

    Group分组划分结果,返回的是分组结果: Facet分组统计,侧重统计,返回的是分组后的数量: 一.Group用法: //组查询基础配置params.set(GroupParams.GROUP, & ...

  2. django 短链接改成长连接

    from django.conf import settings from django.core.wsgi import get_wsgi_application from gunicorn.app ...

  3. 使用ES-Hadoop 6.5.4编写MR将数据索引到ES

    目录 1. 开发环境 2. 下载地址 3. 使用示例 4. 参考文献 1. 开发环境 Elasticsearch 6.5.4 ES-Hadoop 6.5.4 Hadoop 2.0.0 2. 下载地址 ...

  4. 30. Substring with Concatenation of All Words (String; HashTable)

    You are given a string, s, and a list of words, words, that are all of the same length. Find all sta ...

  5. Spring Boot 简单入门

    添加相关依赖 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http ...

  6. c语言静态断言

    在php中可以通过xdebug来显示详细的错误信息,可以细化到哪个文件哪行代码引起的报错.在C语言里面也可以通过静态断言(assert)来使得调试代码更加方便.关于断言,可以作为一种很强大的调试方式或 ...

  7. Qt Image Water Marker

    QString str = "input.jpg"; if(!img.load(str)){ return; } QImage mark(img.width()/2,img.hei ...

  8. web图形方案比较html5、GML、SVG、VML

    GML.SVG和VML都是基于XML的可用来描述矢量图形的标记语言,都是XML词表,它们的语法并不难理解,但它们都有各自不同的用途和特点,下面简单介绍一下. GML(Geography Markup  ...

  9. SQLite介绍

    优点:轻量级.绿色组件.单一文件.跨平台.查询效率极高.使用事务插入速度极快.支持limit分页. 适合查询速度要求较高,内存占用较少的场合,尤其是嵌入式操作系统,如各种手机操作系统,低并发web(9 ...

  10. 分布式java应用基础与实践

      始读于2014年4月30日,完成于2014年6月6日15:43:39. 阿里巴巴高级研究员林昊早年的书了,这些理论放到今天估计工作一两年的人都耳熟能详了,我个人很早以前就知道此书一直没有找到资源, ...