Windows服务使用标准的Csharp编写,任务调度框架采用开源的Quartz.NET。
首先创建Windows服务-JobService
其次创建类库项目-JobLibrary
整体解决方案架构图如下:
在JobLibary中添加Quartz.NET的Nuget包引用,添加之后,vs会自动添加一系列的依赖项,这些依赖项是必须的,别手抖删掉了。
其次再添加Common.Logging.Log4Net1211的Nuget包,他是Log4net的另外一种实现,会自动添加log4net的依赖
所有添加的包如下图:
下面开始添加任务,在libary中添加一个job类继承IJob,并实现其接口
using System;
using Quartz;
namespace JobLibrary
{
public class Job : IJob
{
private static readonly Common.Logging.ILog logger = Common.Logging.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public void Execute(IJobExecutionContext context)
{
try
{
logger.Info("job开始");
using (System.IO.StreamWriter sw = new System.IO.StreamWriter("E:\\log.txt", true))
{
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + " 吃饭---睡觉");
}
logger.Info("job结束");
}
catch (Exception e)
{
logger.Error(e.Message);
}
}
}
}
这个类就是你需要做的任务。我的任务是吃饭和睡觉。
然后再在JobService中添加JobLibrary的引用,并且添加如下代码(需要同样添加Nuget引用)
using Common.Logging;
using Quartz;
using Quartz.Impl;
using System.ServiceProcess;
namespace JobService
{
public partial class Service1 : ServiceBase
{
private IScheduler scheduler;
private readonly ILog logger;
public Service1()
{
InitializeComponent();
ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
scheduler = schedulerFactory.GetScheduler();
logger = LogManager.GetLogger(GetType());
}
protected override void OnStart(string[] args)
{
logger.Info("Quartz服务成功启动");
scheduler.Start();
}
protected override void OnStop()
{
scheduler.Shutdown(false);
}
}
}
代码完成之后,需要配置quartz_jobs.xml,在JobService项目添加xml配置文件“quartz_jobs.xml”,并添加任务配置。
<?xml version="1.0" encoding="UTF-8"?>
<!-- This file contains job definitions in schema version 2.0 format -->
<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>
<!--定义示例任务1 Job-->
<job>
<name>DemoJob1</name>
<group>DeomJobGroup</group>
<description>Quartz.Net示例任务1</description>
<job-type>JobLibrary.Job,JobLibrary</job-type>
<durable>true</durable>
<recover>false</recover>
</job>
<!--定义示例任务1 触发器 每10秒执行一次DemoJob1任务-->
<trigger>
<cron>
<name>DemoJob1Trigger</name>
<group>DeomJobTriggerGroup</group>
<job-name>DemoJob1</job-name>
<job-group>DeomJobGroup</job-group>
<cron-expression>0/10 * * * * ?</cron-expression>
</cron>
</trigger>
</schedule>
</job-scheduling-data>
这个配置文件有个莫名其妙的bug,就是最上面那几行不能有空行,不知道是什么情况,有知道伙计望告知。被这个坑了半天。
其次,在添加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 = 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
然后就是app.config的quartz的配置了
<configSections>
<section name="quartz" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging"/>
</sectionGroup>
</configSections>
然后就是编译,记住quartz_jobs.xml和quartz.config这两个文件一定要编译输出,要不然读取不到。
启动之后,就可以看到写到文件中的内容了。
如果一台机器上跑任务,那么如果这太机器挂掉了怎么办?如果是多台机器上跑任务,那么任务重复执行怎么办?