一、前言运用场景

 quartz.net是一个强大、开源、轻量的作业调度框架,在平时的项目开发当中也会时不时的需要运用到定时调度方面的功能,例如每日凌晨需要统计前一天的数据,又或者每月初需要统计上月的数据。当然也会出现既要统计日的也统计月的还需要进行其他的操作。那我们改如何来写这样的调度任务呢?

二、实际运用(.net core 2.2)

在一个解决方案中创建一个.net控制台应用程序及一个类库,控制台应用程序用来作为程序的启动点。类库用来作为调度任务的执行程序。

然后我们需要完善一下项目的结构,首先我们得在控制台应用程序中创建一个startup类,这个类也是任务启动的一个重要条件。

public class startup
  {

    public startup(iconfiguration configuration)
    {

      configuration = configuration;

    }

    public iconfiguration configuration { get; }

    // this method gets called by the runtime. use this method to add services to the container.

    public void configureservices(iservicecollection services)
    {

      services.addmvc().setcompatibilityversion(compatibilityversion.version_2_2);

    }

 

    // this method gets called by the runtime. use this method to configure the http request pipeline.
    public void configure(iapplicationbuilder app, ihostingenvironment env)
    {

      if (env.isdevelopment())
      {
        app.usedeveloperexceptionpage();
      }
      else
      {
        app.useexceptionhandler("/error");
      }
      app.usemvc();
    }
  }

然后项目会报一定的错误,根据错误信息一步一步解决,解决方案:添加nuget包 microsoft.aspnetcore

解决错误信息之后意味着目前启动程序还算ok了,接下来我们可以详细讲下quartz调度任务执行。

因为我们肯定不仅仅执行一个调度任务,实际项目运行中肯定是多个调度任务一起执行的,所以我们思路可以转变一下。在类库创建一个公共启动中心,同时引用nuget包:quartz。然后开始创建调度任务的公共核心

private ischeduler scheduler;
    /// <summary>

    /// 创建调度任务的入口

    /// </summary>

    /// <returns></returns>

    public async task start()
    {
      await startjob();
    }

    /// <summary>
    /// 创建调度任务的公共调用中心
    /// </summary>
    /// <returns></returns>
    public async task startjob()
    {
      //创建一个工厂
      namevaluecollection param = new namevaluecollection()
      {
        { "testjob","test"}
      };

      stdschedulerfactory factory = new stdschedulerfactory(param);
      //创建一个调度器
      scheduler = await factory.getscheduler();
      //开始调度器
      await scheduler.start();

      //每三秒打印一个info日志
      await createjob<startloginfojob>("_startloginfojob", "_startloginfojob", " 0/3 * * * * ? ");

      //每五秒打印一个debug日志
      await createjob<startlogdebugjob>("_startlogdebugjob", "_startlogdebugjob", " 0/5 * * * * ? ");

      //调度器时间生成地址--    http://cron.qqe2.com

    }

    /// <summary>
    /// 停止调度器      
    /// </summary>
    public void stop()
    {
      scheduler.shutdown();
       scheduler=null;
    }

    /// <summary>
    /// 创建运行的调度器
    /// </summary>
    /// <typeparam name="t"></typeparam>
    /// <param name="name"></param>
    /// <param name="group"></param>
    /// <param name="crontime"></param>
    /// <returns></returns>
    public async task createjob<t>(string name,string group, string crontime) where t: ijob
    {
      //创建一个作业
      var job = jobbuilder.create<t>()
        .withidentity("name" + name, "gtoup" + group)
        .build();

      //创建一个触发器
      var tigger = (icrontrigger)triggerbuilder.create()
        .withidentity("name" + name, "group" + group)
        .startnow()
        .withcronschedule(crontime)
        .build();

      //把作业和触发器放入调度器中
      await scheduler.schedulejob(job, tigger);
    }

然后再去创建两个执行业务逻辑的类,分别是startloginfojob和startlogdebugjob

public class startloginfojob:ijob
  {
    public async task execute(ijobexecutioncontext context)
    {
      await start();
    }
    public async task start()
    {
      loghelp.debug("调度打印debug");
    }
  }

 
public class startlogdebugjob : ijob
  {
    public async task execute(ijobexecutioncontext context)
    {
      await start();
    }
    public async task start()
    {
      loghelp.info("调度打印info");
    }
  }

到这里就顺利的完成了一个定时调度器来执行任务了,最后我们得把这个program文件重新写一下,控制台应用程序生成的program文件不太符合我们需要要求,同时把调度器在这里面启动。

class program
  {
    static void main(string[] args)
    {
      handlestart();
      var webhostargs = args.where(arg => arg != "--console").toarray();
      var host = webhost.createdefaultbuilder(webhostargs)
        .usestartup<startup>()
        .usekestrel(options => {
          options.limits.minrequestbodydatarate = null;
        })
        .build();
      host.run();
    }
    static void handlestart()
    {
      try
      {
        new scheduler().start().getawaiter().getresult();
      }
      catch (exception ex)
      {
        loghelp.error(ex);
      }
    }
  }

我们去看文件夹下面log文件会发现有一个debug和一个info

到这里我们的调度就完成了,我们需要使用的时候将打印日志更换成我们日常想要处理的业务逻辑就可以了。刚刚提到打印日志就顺便提一下在.net core中如何打印日志吧。

三、.net cor打印日志文件

打印日志文件主要是用到了nuget包:nlog,然后再加上一个nlog.config,首先在项目中安装nlog的包,然后创建一个loghelper的公共类。

public class loghelp
  {
    static nlog.logger logger = nlog.logmanager.getcurrentclasslogger();

    public static void debug(string info)
    {
      logger.debug(info);
    }

    public static void info(string info)
    {
      logger.info(info);
    }

    public static void error(exception ex, string info = "")
    {
      logger.error(ex);
    }

}

然后再添加一个nlog.config文件

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/nlog.xsd"
  xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" autoreload="true">

 <targets>
  <target name="defaultlog" xsi:type="file" keepfileopen="false" encoding="utf-8"
    filename="${basedir}/logs/${level}/${shortdate}.log"
    layout="${longdate}|${level:uppercase=true}|${logger}|${message}" />
 </targets>

 <rules>
  <logger name="*" minlevel="trace" writeto="defaultlog" />
 </rules>
</nlog>

完成这两个就可以实现日志的打印了。。

以上所述是www.887551.com给大家介绍的.net core使用quartz执行调度任务进阶详解整合,希望对大家有所帮助