欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.netcore控制台->定时任务Quartz

程序员文章站 2022-08-28 23:11:01
之前做数据同步时,用过timer、window服务,现在不用那么费事了,可以使用Quartz,并且配置灵活,使用cron表达式配置XML就可以。我用的是3.0.7版本支持.netcore。 首先创建一个.netcore控制台应用程序,添加Quartz、Quartz.Jobs、Quartz.Plugi ......

  之前做数据同步时,用过timer、window服务,现在不用那么费事了,可以使用quartz,并且配置灵活,使用cron表达式配置xml就可以。我用的是3.0.7版本支持.netcore。

  • 首先创建一个.netcore控制台应用程序,添加quartz、quartz.jobs、quartz.plugins引用,这里面添加了postgresql数据库的连接方法,其它数据库可以做为参考,添加npgsql、npgsql.entityframeworkcore.postgresql引用,目录结构如下
  • .netcore控制台->定时任务Quartz
  • 创建数据库dbcontext类
  • using system;
    using system.collections.generic;
    using system.text;
    using microsoft.entityframeworkcore;
    
    namespace quartzpro.dbcontext
    {
        public class postgredbcontext : microsoft.entityframeworkcore.dbcontext
        {
            private string _conn;
            public postgredbcontext(dbcontextoptions<postgredbcontext> options) : base(options)
            {
            }
            public postgredbcontext(string conn)
            {
                _conn = conn;
            }
    
            protected override void onmodelcreating(modelbuilder builder)
            {
                base.onmodelcreating(builder);
                //builder.entity<syrequest_main>().totable("book", "pro");
            }
             
           // public virtual dbset<book> book { get; set; }
    
        }
    }

     

  • 创建job类
  • using system;
    using system.collections.generic;
    using system.io;
    using system.text;
    using system.threading.tasks;
    using microsoft.extensions.logging;
    using quartz;
    
    namespace quartzpro.jobs
    {
        public class syncuserinfoservice : ijob
        {
            private readonly ilogger<syncuserinfoservice> _logger;
    
            public syncuserinfoservice()
            {
                _logger = bootstrapioc.getservice<iloggerfactory>().createlogger<syncuserinfoservice>();
            }
            public task execute(ijobexecutioncontext context)
            {
                _logger.logdebug($"syncuserinfoservice execute start...");
                return task.run(() =>
                {
                    using (streamwriter sw = new streamwriter(@"d:\print.txt", true, encoding.utf8))
                    {
                        sw.writeline(datetime.now + "任务执行中...");
                        sw.close();
                    }
                });
            }
        }
    }

     

  • 创建依赖注入类
  • using microsoft.extensions.configuration;
    using microsoft.extensions.dependencyinjection;
    using microsoft.extensions.logging;
    using quartzpro.dbcontext;
    
    namespace quartzpro
    {
        public static class bootstrapioc
        {
            /// <summary>
            /// ioc容器
            /// </summary>
            private static iservicecollection servicecollection { get; } = new servicecollection();
    
            /// <summary>
            /// 初始化ioc容器
            /// </summary>
            public static void initioc()
            {
    
                var configuration = new configurationbuilder().addjsonfile("appsettings.json", optional: true, reloadonchange: true).addenvironmentvariables().build();
    
                var identityconn = configuration.getconnectionstring("identityconnection");
                //db
                servicecollection.addtransient(_ => new  postgredbcontext(identityconn));
                //log
                servicecollection.addlogging(configure =>
                {
                    configure.addconfiguration(configuration.getsection("logging"));
                    configure.addconsole();
                });
                //config
                servicecollection.addsingleton<iconfiguration>(configuration);
          
            }
    
            /// <summary>
            /// 获取实体
            /// </summary>
            /// <typeparam name="t"></typeparam>
            /// <returns></returns>
            public static t getservice<t>()
            {
                return servicecollection.buildserviceprovider().getservice<t>();
            }
        }
    }
    

      

  • 创建任务监听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>
      
        <!--同步用户信息:10分钟一次-->
        <job>
          <name>syncuserinfoservice</name>
          <group>groupuserinfomanager</group>
          <description>同步用户信息</description>
          <job-type>quartzpro.jobs.syncuserinfoservice, quartzpro</job-type>
          <durable>true</durable>
          <recover>false</recover>
        </job>
        <trigger>
          <cron>
            <name>triggersyncuserinfoservice</name>
            <group>grouptriggeruserinfomanager</group>
            <job-name>syncuserinfoservice</job-name>
            <job-group>groupuserinfomanager</job-group>
            <start-time>2019-07-30t15:15:00.0z</start-time>
            <cron-expression>0 0/10 * * * ?</cron-expression>
            <!--<cron-expression>1 0 0 * * ?</cron-expression>-->
          </cron>
        </trigger>
      </schedule>
    </job-scheduling-data>

     

  • json配置文件
  • {
      "logging": {
        "loglevel": {
          "default": "debug",
          "system": "information",
          "microsoft": "information"
        },
        "console": {
          "includescopes": true
        }
      },
      "connectionstrings": {
        "identityconnection": "user id=admin;password=123456;host=.;port=5432;database=identities;"
      }
    }

     

  • program类,注意该项目为控制台程序 userinfomanager.xml和 appsettings.json,需要右键设置为可输出文件

  • using system; using system.collections.specialized; using system.threading.tasks; using quartz; using quartz.impl; namespace quartzpro { class program { private static void main(string[] args) { bootstrapioc.initioc(); var task = run(); task.wait(); task.configureawait(false); while (true) { console.read(); } } public static async task run() { try { var properties = new namevaluecollection { ["quartz.plugin.trigghistory.type"] = "quartz.plugin.history.loggingjobhistoryplugin, quartz.plugins", ["quartz.plugin.jobinitializer.type"] = "quartz.plugin.xml.xmlschedulingdataprocessorplugin, quartz.plugins", ["quartz.plugin.jobinitializer.filenames"] = "userinfomanager.xml", ["quartz.plugin.jobinitializer.failonfilenotfound"] = "true", ["quartz.plugin.jobinitializer.scaninterval"] = "120" }; ischedulerfactory sf = new stdschedulerfactory(properties); ischeduler scheduler = await sf.getscheduler(); console.writeline("start the schedule"); await scheduler.start(); console.writeline("end"); } catch (schedulerexception se) { await console.error.writelineasync(se.tostring()); } catch (exception ex) { console.write($"err={ex.tostring()}"); } } } }