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这两个文件一定要编译输出,要不然读取不到。
启动之后,就可以看到写到文件中的内容了。
如果一台机器上跑任务,那么如果这太机器挂掉了怎么办?如果是多台机器上跑任务,那么任务重复执行怎么办?
运维网声明
1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网 享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com