.net定时任务(作业)-简单说

我要给大家介绍一个开源的作业调度框架Quartz.NET,

有一些工作需要定时轮询数据库同步,定时邮件通知,定时处理数据 可以选择Quartz.NET。

快速搭建一个Quartz

1.创建一个控制台应用程序

2.安装依赖包(类库)

  • Install-Package Quartz
  • Install-Package Common.Logging.Log4Net1211
  • Install-Package log4net
  • Install-Package Topshelf  --最关键的创建服务的
  • Install-Package Topshelf.Log4Net

 Quartz依赖Common.Logging和Common.Logging.Log4Net1211,又因为Log4Net是比较标准的日志工具,因此我们一般都会安装log4net,另外定时作业一般都允许在后台服务中,因此我们也安装了Topshelf。


3.创建要定时执行的类继承IJop

using Quartz;
using log4net;
using System;

namespace ExtendService
{
    class Maplnglat : IJob
    {
        private readonly ILog _logger = LogManager.GetLogger(typeof(Maplnglat));
        public void Execute(IJobExecutionContext context)
        {
            try
            {
                _logger.InfoFormat("TestJob测试");
            }
            catch (Exception e)
            {
                _logger.Error("error:" + DateTime.Now.ToString("yyyy-MM-dd") + "获取失败:" + e.Message, e);
            }
        }


    }
}

using Quartz;
using log4net;
using System;

namespace ExtendService
{
    class Maplnglat : IJob
    {
        private readonly ILog _logger = LogManager.GetLogger(typeof(Maplnglat));
        public void Execute(IJobExecutionContext context)
        {
            try
            {
                _logger.InfoFormat("TestJob测试");
            }
            catch (Exception e)
            {
                _logger.Error("error:" + DateTime.Now.ToString("yyyy-MM-dd") + "获取失败:" + e.Message, e);
            }
        }


    }
}
4.定义Topshelf调度服务 

using log4net;
using Quartz;
using Quartz.Impl;
using Topshelf;
using System;
namespace ExtendService
{
    public class QuartzWS : ServiceControl, ServiceSuspend
    {
        private readonly ILog _logger = LogManager.GetLogger(typeof(QuartzWS));
        private readonly IScheduler scheduler;


        public QuartzWS()
        {
            scheduler = StdSchedulerFactory.GetDefaultScheduler();
        }


        public bool Start(HostControl hostControl)
        {
            _logger.InfoFormat(@"开始服务:{0}", DateTime.Now);
            scheduler.Start();
            return true;
        }


        public bool Stop(HostControl hostControl)
        {
            _logger.InfoFormat(@"停止服务:{0}", DateTime.Now);
            scheduler.Shutdown(false);
            return true;
        }


        public bool Continue(HostControl hostControl)
        {
            _logger.InfoFormat(@"继续服务:{0}", DateTime.Now);
            scheduler.ResumeAll();
            return true;
        }


        public bool Pause(HostControl hostControl)
        {
            _logger.InfoFormat(@"暂停服务:{0}", DateTime.Now);
            scheduler.PauseAll();
            return true;
        }
    }
}

using Quartz;
using log4net;
using System;

namespace ExtendService
{
    class Maplnglat : IJob
    {
        private readonly ILog _logger = LogManager.GetLogger(typeof(Maplnglat));
        public void Execute(IJobExecutionContext context)
        {
            try
            {
                _logger.InfoFormat("TestJob测试");
            }
            catch (Exception e)
            {
                _logger.Error("error:" + DateTime.Now.ToString("yyyy-MM-dd") + "获取失败:" + e.Message, e);
            }
        }


    }
}
5.程序入口添加

    static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"));
            HostFactory.Run(x =>
            {
                x.Service<QuartzWS>();
                x.RunAsLocalSystem();
                x.SetDescription("调用百度API获取经纬度,Quartz");
                x.SetDisplayName("调用百度API获取经纬度");
                x.SetServiceName("GetLngLat");   
            });
        }

6.项目中添加三个配置文件quartz.config、quartz_jobs.xmllog4net.config

说明:这三个文件,分别选中→右键属性→复制到输入目录设为:始终复制



1.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>    
    <job>
      <name>Maplnglat</name>
      <group>Maplnglat</group>
      <description>经纬度获取</description>
      <job-type>SinoOcean.DataVisual.ExtendService.Maplnglat,SinoOcean.DataVisual.ExtendService</job-type>
      <durable>true</durable>
      <recover>false</recover>
    </job>
    <trigger>
      <cron>
        <name>MaplnglatTrigger</name>
        <group>Maplnglat</group>
        <job-name>Maplnglat</job-name>
        <job-group>Maplnglat</job-group>
        <start-time>2017-07-27T09:00:00+08:00</start-time>
        <cron-expression>0 35 13 * * ?</cron-expression>
      </cron>
    </trigger> 
  </schedule>
</job-scheduling-data>

2.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 = 5556
quartz.scheduler.exporter.bindName = QuartzScheduler
quartz.scheduler.exporter.channelType = tcp
quartz.scheduler.exporter.channelName = httpQuartz

3.log4net.config 内容如下


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  </configSections>


  <log4net>
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <!--日志路径-->
      <param name= "File" value= "D:\App_Log\servicelog\"/>
      <!--是否是向文件中追加日志-->
      <param name= "AppendToFile" value= "true"/>
      <!--log保留天数-->
      <param name= "MaxSizeRollBackups" value= "10"/>
      <!--日志文件名是否是固定不变的-->
      <param name= "StaticLogFileName" value= "false"/>
      <!--日志文件名格式为:2008-08-31.log-->
      <param name= "DatePattern" value= "yyyy-MM-dd&quot;.read.log&quot;"/>
      <!--日志根据日期滚动-->
      <param name= "RollingStyle" value= "Date"/>
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n %loggername" />
      </layout>
    </appender>


    <!-- 控制台前台显示日志 -->
    <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
      <mapping>
        <level value="ERROR" />
        <foreColor value="Red, HighIntensity" />
      </mapping>
      <mapping>
        <level value="Info" />
        <foreColor value="Green" />
      </mapping>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%n%date{HH:mm:ss,fff} [%-5level] %m" />
      </layout>


      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="Info" />
        <param name="LevelMax" value="Fatal" />
      </filter>
    </appender>


    <root>
      <!--(高) OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL (低) -->
      <level value="all" />
      <appender-ref ref="ColoredConsoleAppender"/>
      <appender-ref ref="RollingLogFileAppender"/>
    </root>
  </log4net>
</configuration>


运行后,效果下图



quartz_jobs.xml 配置执行类

主要配置<job-type>  空间名.类名,空间名</job-type>

<start-time>开始时间</start-time>

<cron-expression>cron表达式的配置执行时间<cron-expression>


由7段构成:秒 分 时 日 月 星期 年(可选)
"-" :表示范围  MON-WED表示星期一到星期三
"," :表示列举 MON,WEB表示星期一和星期三
"*" :表是“每”,每月,每天,每周,每年等
"/" :表示增量:0/15(处于分钟段里面) 每15分钟,在0分以后开始,3/20 每20分钟,从3分钟以后开始
"?" :只能出现在日,星期段里面,表示不指定具体的值
"L" :只能出现在日,星期段里面,是Last的缩写,一个月的最后一天,一个星期的最后一天(星期六)
"W" :表示工作日,距离给定值最近的工作日
"#" :表示一个月的第几个星期几,例如:"6#3"表示每个月的第三个星期五(1=SUN...6=FRI,7=SAT)

CRON表达式官方实例

ExpressionMeaning
0 0 12 * * ?每天中午12点触发
0 15 10 ? * *每天上午10:15触发
0 15 10 * * ?每天上午10:15触发
0 15 10 * * ? *每天上午10:15触发
0 15 10 * * ? 20052005年的每天上午10:15触发
0 * 14 * * ?在每天下午2点到下午2:59期间的每1分钟触发
0 0/5 14 * * ?在每天下午2点到下午2:55期间的每5分钟触发
0 0/5 14,18 * * ?在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
0 0-5 14 * * ?在每天下午2点到下午2:05期间的每1分钟触发
0 10,44 14 ? 3 WED每年三月的星期三的下午2:10和2:44触发
0 15 10 ? * MON-FRI周一至周五的上午10:15触发
0 15 10 15 * ?每月15日上午10:15触发
0 15 10 L * ?每月最后一日的上午10:15触发
0 15 10 L-2 * ?Fire at 10:15am on the 2nd-to-last last day of every month
0 15 10 ? * 6L每月的最后一个星期五上午10:15触发
0 15 10 ? * 6LFire at 10:15am on the last Friday of every month
0 15 10 ? * 6L 2002-20052002年至2005年的每月的最后一个星期五上午10:15触发
0 15 10 ? * 6#3每月的第三个星期五上午10:15触发
0 0 12 1/5 * ?Fire at 12pm (noon) every 5 days every month, starting on the first day of the month.
0 11 11 11 11 ?Fire every November 11th at 11:11am.


参考资料

官方学习文档:http://www.quartz-scheduler.net/documentation/index.html

使用实例介绍:http://www.quartz-scheduler.net/documentation/quartz-2.x/quick-start.html

官方的源代码下载:http://sourceforge.net/projects/quartznet/files/quartznet/ 


using Quartz;
using log4net;
using System;

namespace ExtendService
{
    class Maplnglat : IJob
    {
        private readonly ILog _logger = LogManager.GetLogger(typeof(Maplnglat));
        public void Execute(IJobExecutionContext context)
        {
            try
            {
                _logger.InfoFormat("TestJob测试");
            }
            catch (Exception e)
            {
                _logger.Error("error:" + DateTime.Now.ToString("yyyy-MM-dd") + "获取失败:" + e.Message, e);
            }
        }


    }
}
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值