背景
大部分業務都是基于定時的任務,特別適合使用quartz這類框架解決定時問題,具體quartz的使用,看官方檔案就可以了,下面談談對quartz插件化的封裝,我們使用quartz.plugin,然后在quartz_jobs.xml方法里面定義了schedule,其中靈活的地方在于,里面定義了Jobs的屬性,在QuartzPlugin的start方法執行的時候,會去加載quartz_jobs檔案,逐個job資訊進行加載,
解決思路
在實際使用中,開發就變得相對簡單了,不需要關注job任務是如何被調度的,只需要在程式中定義一個類實作job介面,填充業務代碼,然后在檔案里面填寫該job屬性:
[DisallowConcurrentExecution] public class AnalysisJob : IJob { public void Execute(IJobExecutionContext context) { xxxxxxxxxx } } <job> <name>名稱</name> <group>分組</group> <description>描述</description> <job-type>類別庫</job-type> <durable>true</durable> <recover>false</recover> </job>
這樣的封裝就賦予框架新的技能,大大提高了開發人員的開發效率,

主要代碼
using System; using System.Collections.Generic; using System.Linq; using Topshelf; namespace HSCP.Task { class Program { static void Main(string[] args) { HostFactory.Run(x => { x.Service<MainService>((s) => { s.ConstructUsing(settings => new MainService()); s.WhenStarted(tr => tr.Start()); s.WhenStopped(tr => tr.Stop()); }); x.RunAsLocalSystem(); x.SetDescription(""); x.SetDisplayName("xxxx任務管理器"); x.SetServiceName("HSCP.Task"); }); } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Quartz; using Quartz.Impl; namespace HSCP.Task { class MainService { static IScheduler sched; public void Start() { try { ISchedulerFactory factory = new StdSchedulerFactory(); sched = factory.GetScheduler(); sched.Start(); Console.WriteLine($"共 {sched.GetJobGroupNames().Count} 任務"); foreach (string gn in sched.GetJobGroupNames()) Console.WriteLine(gn); } catch (Exception exc) { Console.WriteLine(exc.ToString()); } // NLogger.Info(string.Format("啟動成功 {0}", DateTime.Now)); } public void Stop() { sched.Shutdown(true); } } }
開源地址
https://github.com/quartznet/quartznet
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/247899.html
標籤:C#
上一篇:AE二次開發問題求助
下一篇:C# 創建Excel氣泡圖
