.netcoreのコールWEBAPIは、タスクが定期的にサービスするように構成することができ、組み立て

1.需要

  • 呼び出し可能WEBAPI
  • タスクは、構成ファイルを使用して設定することができます
  • 時間設定のcronにより、
  • ログインすることで、任務の実装
  • Windowsがサービスに閉じることができます
  • これは、クロスプラットフォームの展開の可能性を秘めています

2.選択

  • クロスプラットフォーム.netcore
  • 反復タスクQuartz.net
  • WEBAPI Restsharpを呼び出し
  • 設定WEBAPIのsharpconfig
  • NLogロギング
  • 定休WindowsサービスTopshelf

3.ライブラリのバージョン

nugetによって、次のライブラリをインストール、私はvs2019を使用していますIDE、コンソールプログラムを作成します。

4.プログラム構造

5.これが実質的なニーズに応じて延長後半フレームで、単語は、コードの上に、言っていません。

  • quartz_jobs.xml

    タスクdemojob19内部の構成は、2秒に1回行いました。
<?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>

    <job>
      <name>demojob19</name>
      <group>groupa</group>
      <description>demo</description>
      <job-type>Quartz.Hello.HelloJob,Quartz.Hello</job-type>
      <durable>true</durable>
      <recover>false</recover>
    </job>
    <trigger>
      <cron>
        <name>demotrigger1</name>
        <group>groupa</group>
        <description>demo</description>
        <job-name>demojob19</job-name>
        <job-group>groupa</job-group>
        <cron-expression>*/2 * * * * ?</cron-expression>
      </cron>
    </trigger>
  </schedule>
</job-scheduling-data>
  • QuartzServer.cs
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Threading.Tasks;

namespace Quartz.Hello
{
    class QuartzServer
    {
        private IScheduler scheduler;
        public QuartzServer()
        {
            //初始化相关配置
            RunProgramRunExample().GetAwaiter().GetResult();
        }
        public void Start()
        {
            //启动服务      
            scheduler.Start();
        }
        public void Stop()
        {
            //关闭服务  
            scheduler.Shutdown();
        }
        private async Task RunProgramRunExample()
        {
            try
            {
                // Grab the Scheduler instance from the Factory
                NameValueCollection props = new NameValueCollection
                {
                    { "quartz.serializer.type", "binary" },
                    {"quartz.plugin.xml.type","Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz.Plugins" },
                    {"quartz.plugin.xml.fileNames","quartz_jobs.xml" } //指定任务配置文件
                };
                StdSchedulerFactory factory = new StdSchedulerFactory(props);
                scheduler = await factory.GetScheduler();
                
            }
            catch (SchedulerException se)
            {
                Console.WriteLine(se);
            }
        }

    }
}
  • Program.csの
using Quartz.Impl;
using System;
using System.Collections.Specialized;
using System.Threading.Tasks;
using Topshelf;

namespace Quartz.Hello
{
    public class Program
    {
        private static void Main(string[] args)
        {
            HostFactory.Run(x =>
            {
                x.Service<QuartzServer>(s =>
                {
                    s.ConstructUsing(name => new QuartzServer());
                    s.WhenStarted(tc => tc.Start());
                    s.WhenStopped(tc => tc.Stop());
                });
                x.RunAsLocalSystem();

                x.SetDescription("QuartzNet任务调度服务,通过配置文件执行!");
                x.SetDisplayName("QuartzJobShedule");
                x.SetServiceName("Quartz任务调度框架");
            });
        } 
    }

    public class HelloJob : IJob
    {
        public async Task Execute(IJobExecutionContext context)
        {
            var logger = NLog.LogManager.GetCurrentClassLogger();
            string jobName = context.JobDetail.Key.Name;//获取本次job中的name.对应quartz_jobs.xml中job节点中的name属性
            
            if(Helper.ExecuteRestApi(jobName))//调用远程webapi接口
            {
                logger.Info( jobName + "执行成功!");
            }
            else
            {
                logger.Info(jobName + "执行失败!");
            }

            logger.Info("hello nlog!"+jobName+"正在运行!");
            await Console.Out.WriteLineAsync("Greetings from HelloJob!中国");
            logger.Debug("这是一个调式!");
        }

    }
}
  • Helper.cs
using RestSharp;
using SharpConfig;
using System;
using System.Collections.Generic;
using System.Text;

namespace Quartz.Hello
{
    class Helper
    {
        public static bool ExecuteRestApi(string jobname)
        {
            var config = Configuration.LoadFromFile("sample.cfg");
            var section = config[jobname];
            string url = section["rootUrl"].StringValue;            
            string methed= section["methed"].StringValue;

            var client = new RestClient(url) ;
            var request = new RestRequest(jobname);
            var response= client.Get(request);
            switch (methed) {                
                case "post":
                    response = client.Post(request);
                    break;
            }
            var statusCode = response.StatusCode.ToString();
            return _ = statusCode == "200" ? true : false;
        }
    }
}
  • Jobs.ini
[demojob19]
# a job
rootUrl = http://localhost:6001/api/
methed  = get
  • 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">

  <targets>
    <target name="logfile" xsi:type="File" fileName="filelog.txt" />
    <target name="logconsole" xsi:type="Console" />
  </targets>

  <rules>
    <logger name="*" minlevel="Info" writeTo="logconsole" />
    <logger name="*" minlevel="Debug" writeTo="logfile" />
  </rules>
</nlog>

6.それを実行します

dotnet Quartz.Hello.dll

7.サービスウィンドウを使用する方法はTopShelfマウント

#安装服务
Quartz.Hello.exe install

#启动服务
Quartz.Hello.exe start

#卸载服务
Quartz.Hello.exe uninstall

私たちは完了です。簡単ではありません!

おすすめ

転載: www.cnblogs.com/ihappycat/p/11795051.html