大部分業務都是基於定時的任務,特別適合使用quartz這類框架解決定時問題。具體quartz的使用,看官方文檔就能夠了。下面談談對quartz插件化的封裝。咱們使用quartz.plugin。而後在quartz_jobs.xml方法裏面定義了schedule,其中靈活的地方在於,裏面定義了Jobs的屬性,在QuartzPlugin的start方法執行的時候,會去加載quartz_jobs文件,逐個job信息進行加載。git
在實際使用中,開發就變得相對簡單了,不須要關注job任務是如何被調度的。只須要在程序中定義一個類實現job接口,填充業務代碼,而後在文件裏面填寫該job屬性:github
[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編輯器