.netcore控制台->定時任務Quartz

来源:https://www.cnblogs.com/personblog/archive/2019/07/31/11277527.html
-Advertisement-
Play Games

之前做數據同步時,用過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引用,目錄結構如下
  • 創建資料庫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()}"); } } } } 

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 鑒於前面學了不少基礎了,今天沒有學新的內容。boyfriend給我出了幾道簡單的題目,慢慢的進步中。 ...
  • 傳入一個參數 --功能:如果是純數字的話返回:這是一串數字,如果是英文或者英文加數字,就把所有的英文轉化為大寫 運行結果如下為: 第二種方法:用內置函數 運行結果如下: ...
  • 原文地址:https://www.cnblogs.com/younShieh/p/11279420.html   項目中遇到一個難題,需要將上百個沒有顯示出來的Canvas存儲為圖片保存在本地。 1 . 查閱資料後(百度一下)後得知保存為本地圖片可以通過BitmapSource的 ...
  • 1、MVC中的TempData\ViewBag\ViewData區別? 答:頁面對象傳值,有這三種對象可以傳。 Temp:臨時的 Bag:袋子 (1) TempData 保存在Session中,Controller每次執行請求的時候,會從Session中先獲取 TempData,而後清除Sessio ...
  • 1、將一個值類型變數賦給另一個值類型變數時,將複製包含的值。引用變數的賦值只複製對對象的引用,而不複製對象本身。 2、值類型不可能派生出新的類型:所有的值類型均隱式派生自 System.ValueType.但與引用類型相同的是,結構也可以實現介面。 3、值類型不可能包含null 值;然後,可空類型功 ...
  • 1.改變RectTransform的Left和Buttom offsetMax是一個Vector2類型 offsetMax.x即為RectTransform中的Left offsetMax.y即為RectTransform中的Buttom 2.改變RectTransform的Right和Top of ...
  • 1、Connection:主要是開啟程式和資料庫之間的連接。沒有利用連接對象將資料庫打開,是無法從資料庫中取得數據的。 Close和Dispose的區別,Close以後還可以Open,Dispose以後則不能再用。 2、Command:主要可以用來對資料庫發出一些指令,例如可以對資料庫下達查詢、新增 ...
  • 問道 面向Abp 在面向服務的時候,Session 幹嘛用? 先把Session 的作用說了,但是在微服務環境下給忽略了,相當於忽略了核心。 Session 只是個功能。就是根據Cookie 的SessionId 得到的一個KeyValue列表 實際上Session 就是一個緩存可以向寫東西,讀東西 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...