最近項目須要作一寫任務做業調度的工做,最終選擇了quartz.net這個插件,它提供了巨大的靈活性而不犧牲簡單性。你可以用它來爲執行一個做業而 建立簡單的或複雜的調度。它有不少特徵,如:數據庫支持,集羣,插件,支持cron-like表達式等等.對於quartz.net在這就不進行過的介紹 了,下面針對這個插件的封裝具體以下。html
quartz.net的封裝主要包括:git
1.任務的基本操做(建立,刪除,暫停,繼續,狀態查詢,數量查詢等)github
2.任務執行觸發動做的回調,其中回調用有兩種委託雷響Action,Action<IQjob>數據庫
3.持久化的處理,持久化文件保存到xml文件中(一個任務一個xml文件)數組
對象分爲對位接口(IQJob)和內部操做接口(IMJob).除了對象自己,接口還包括對對象的一些簡單操做,好比Remove,pause,Resume等.這樣的目的是爲了讓對象更便與操做。ide
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Quartz { /// <summary> /// quartz.net接口對象 /// 做者:王延領 /// 時間:2016/5/5 /// </summary> public interface IQJob { /// <summary> /// 系統代碼 /// </summary> string SysCode { get; set; } /// <summary> /// 任務id /// </summary> string JobId { get; set; } /// <summary> /// 任務名稱 /// </summary> string Name { get; set; } /// <summary> /// 任務分組 /// </summary> string Group { get; set; } /// <summary> /// 間隔時間 /// </summary> int Seconds { get; set; } /// <summary> /// 作多執行次數,若是是<1,則無限循環 /// </summary> int MaxTimes { get; set; } /// <summary> /// 開始執行時間 /// </summary> DateTime StartTime { get; set; } /// <summary> /// 任務處理器 /// </summary> Action Handler { get; set; } /// <summary> /// 任務處理器 /// </summary> Action<IQJob> DetailHandler { get; set; } /// <summary> /// 當前執行的第幾回 /// </summary> int Times { get; set; } /// <summary> /// 接口執行時間 /// </summary> DateTime LastTime { get; set; } /// <summary> /// 任務的當前狀態 /// </summary> JobState State { get; set; } /// <summary> /// 本次任務執行的動做 /// </summary> JobAction Action { get; set; } /// <summary> /// 開始執行任務 /// </summary> void Start(); /// <summary> /// 開始執行任務 /// </summary> /// <param name="starttime">任務開始時間</param> /// <param name="internaltimes">間隔時間(s)</param> /// <param name="maxtimes">執行次數</param> void Start(DateTime starttime, int internaltimes = 60*60, int maxtimes = 0); /// <summary> /// 任務觸發動做 /// 無需參數 /// </summary> /// <param name="action">觸發的動做</param> /// <returns></returns> IQJob Handle(Action handler); /// <summary> /// 任務觸發動做 /// </summary> /// <param name="action">觸發的動做</param> /// <returns></returns> IQJob Handle(Action<IQJob> handler); string Key(); bool Load(); bool Save(); /// <summary> /// 下次運行時間 /// </summary> DateTime NextTime(); /// <summary> /// 獲取job文件地址 /// </summary> /// <returns></returns> string Path(); /// <summary> /// 移除 /// </summary> /// <returns></returns> bool Remove(); /// <summary> /// 掛起 /// </summary> void Pause(); /// <summary> ///繼續執行 /// </summary> void Resume(); } } using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Quartz { public interface IMyJob : IQJob { void Excute(); void QRemove(); void QPause(); void QResume(); } }
quartz.net對的封裝主要包括:函數
1.任務的基本操做(建立,刪除,暫停,繼續,狀態查詢,數量查詢等)post
2.任務執行觸發動做的回調,其中回調用有兩種委託雷響Action,Action<IQjob>測試
3.持久化的處理,持久化文件保存到xml文件中(一個任務一個xml文件)ui
using Quartz; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Quartz { /// <summary> /// quartz.net任務調度接口 /// 做者:王延領 /// 日期:2016/5/5 /// </summary> public interface IJobFactory { /// <summary> /// 任務觸發的動做 /// </summary> /// <param name="syscode">系統編碼</param> /// <param name="hander">須要參數的觸發動做</param> void Trigger(string syscode, Action<IQJob> hander); /// <summary> /// 任務觸發的動做 /// </summary> /// <param name="syscode">系統編碼</param> /// <param name="hander">無需參數的觸發動做</param> void Trigger(string syscode, Action hander); /// <summary> /// 建立任務 /// </summary> /// <param name="job"> IQJob</param> /// <returns></returns> string Build(IQJob job); /// <summary> /// 移除任務 /// </summary> /// <param name="jobid">IMyJob.Key()</param> /// <returns></returns> bool Remove(string jobkey); /// <summary> /// 暫停任務 /// </summary> /// <param name="jobkey">IMyJob.Key()</param> /// <returns></returns> bool Pause(string jobkey); /// <summary> /// 繼續任務 /// </summary> /// <param name="jobkey">IMyJob.Key()</param> /// <returns></returns> bool Resume(string jobkey); /// <summary> /// 任務是否存在 /// </summary> /// <param name="jobkey">IMyJob.Key()</param> /// <returns></returns> bool Exists(string jobkey); /// <summary> /// 移除任務 /// </summary> /// <param name="systcode">系統編碼</param> void RemoveAll(string systcode); /// <summary> /// 暫停任務 /// </summary> /// <param name="syscode">系統編碼</param> void PauseAll(string syscode); /// <summary> /// 繼續任務 /// </summary> /// <param name="syscode">系統編碼</param> void ResumeAll(string syscode); /// <summary> /// 任務數 /// </summary> /// <param name="syscode">系統編碼</param> /// <param name="state">任務狀態</param> /// <returns></returns> int JobCount(string syscode, JobState state); /// <summary> /// 任務數 /// </summary> /// <returns></returns> int JobCount(); /// <summary> /// 任務狀態 /// </summary> /// <param name="jobkey">IMyJob.Key()</param> /// <returns></returns> JobState State(string jobkey); /// <summary> /// 獲取任務 /// </summary> /// <param name="jobkey">IMyJob.Key()</param> /// <returns></returns> IMyJob FindByKey(string jobkey); /// <summary> /// 任務初始化 /// </summary> void Initialize(); } }
此接口的實現主要包括兩部分:
1.對外操做的建立,刪除,暫停,繼續,狀態和個數的查詢,對象load和sava
2.執行job操做是進行動做觸發的操做。
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Quartz { public class MyJob : QJob, IMyJob { public MyJob() { } public MyJob(IQJob qjob) { this.Action = qjob.Action; this.SysCode = qjob.SysCode; this.JobId = qjob.JobId; this.Group = qjob.Group; this.Name = qjob.Name; this.LastTime = qjob.LastTime; this.MaxTimes = qjob.MaxTimes; this.Seconds = qjob.Seconds; this.State = qjob.State; this.Times = qjob.Times; this.StartTime = qjob.StartTime; this.DetailHandler = qjob.DetailHandler; this.Handler = qjob.Handler; } /// <summary> ///任務執行時觸發動做 /// </summary> public void Excute() { try { Times++; LastTime = DateTime.Now; Action = JobAction.Excute; if (MaxTimes == 1) { XMLProcess.Delete(Path()); MaxTimes = 0; Trigger(); return; } if (MaxTimes != 0) MaxTimes--; Save(); Trigger(); } catch (Exception ex) { } } /// <summary> ///任務暫停時觸發動做 /// </summary> public void QPause() { Action = JobAction.Pend; State = JobState.Pending; Save(); Trigger(); } /// <summary> /// 任務繼續時觸發動做 /// </summary> public void QResume() { Action = JobAction.Resume; State = JobState.Working; Save(); Trigger(); } /// <summary> /// 任務移除觸發動做 /// </summary> public void QRemove() { XMLProcess.Delete(Path()); Action = JobAction.Delete; Trigger(); } /// <summary> /// <summary> /// 動做觸發 /// </summary> /// <param name="myjob">JobDetail</param> void Trigger() { if (Handler != null) { Handler(); return; } if (DetailHandler != null) { DetailHandler(this); return; } //獲取訂閱委託列表 var sh = JobVariables.GetHandlers.SingleOrDefault(h => h.systme_code == SysCode); if (sh.detailexcute != null) { sh.detailexcute(this); return; } if (sh.excute != null) sh.excute(); } } } using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Quartz { /// <summary> /// quartz.net對象 /// 做者:王延領 /// 時間:2016/5/5 /// </summary> public class QJob : IQJob { /// <summary> /// 構造函數 /// </summary> public QJob() { } /// <summary> /// 構造函數 /// </summary> /// <param name="syscode">系統編碼</param> /// <param name="id">任務id【需系統內惟一】</param> /// <param name="name">任務名稱</param> /// <param name="group">任務羣組</param> public QJob(string syscode, string id, string name = "", string group = "") { JobId = id; SysCode = syscode; Name = name; Group = group; Seconds = 60 * 60; MaxTimes = 0; StartTime = DateTime.Now.AddMinutes(1); Handler = null; DetailHandler = null; } public string SysCode { get; set; } public string JobId { get; set; } public string Name { get; set; } public string Group { get; set; } public int Seconds { get; set; } public int MaxTimes { get; set; } public DateTime StartTime { get; set; } public int Times { get; set; } public JobState State { get; set; } public JobAction Action { get; set; } public DateTime LastTime { get; set; } [System.Xml.Serialization.XmlIgnore] public Action Handler { get; set; } [System.Xml.Serialization.XmlIgnore] public Action<IQJob> DetailHandler { get; set; } /// 持久化保存 /// </summary> public bool Save() { try { string filepath = JobFactory.Instance.GetPath(); if (!File.Exists(Path())) return false; IQJob myjob = new QJob() { SysCode = this.SysCode, JobId = this.JobId, Group = this.Group, Name = this.Name, LastTime = this.LastTime, Handler = this.Handler, MaxTimes = this.MaxTimes, Seconds = this.Seconds, State = this.State, Times = this.Times, StartTime = this.StartTime, DetailHandler = this.DetailHandler, Action = this.Action }; string xml = XMLProcess.Serializer(typeof(QJob), myjob); XMLProcess.Write(xml, Path()); return true; } catch (Exception ex) { return false; } } public bool Load() { try { var job = XMLProcess.Deserialize<QJob>(XMLProcess.ReadXml(Path())); JobId = job.JobId; SysCode = job.SysCode; Name = job.Name; Group = job.Group; Seconds = job.Seconds; MaxTimes = job.MaxTimes; StartTime = job.StartTime; Times = job.Times; State = job.State; Action = job.Action; LastTime = job.LastTime; return true; } catch (Exception ex) { return false; } } /// <summary> /// 任務的jobkey規則 /// </summary> /// <returns></returns> public string Key() { return SysCode + "_" + JobId; } /// <summary> /// 開始執行任務 /// </summary> public void Start() { JobFactory.Instance.Build(this); } /// <summary> /// 開始執行任務 /// </summary> /// <param name="starttime">開始執行時間</param> /// <param name="internaltimes">時間間隔(s)</param> /// <param name="maxtimes">執行次數</param> public void Start(DateTime starttime, int internaltimes = 60*60, int maxtimes = 0) { StartTime = starttime; Seconds = internaltimes; MaxTimes = maxtimes; JobFactory.Instance.Build(this); } /// <summary> /// 下次執行時間 /// </summary> /// <returns></returns> public DateTime NextTime() { return LastTime.AddSeconds(Seconds); } /// <summary> ///任務觸發動做 /// </summary> /// <param name="handler">須要任務信息的動做</param> /// <returns>IMyJob</returns> public IQJob Handle(Action handler) { Handler = handler; return this; } /// <summary> /// 任務觸發動做 /// </summary> /// <param name="handler">須要任務信息的動做</param> /// <returns>IMyJob</returns> public IQJob Handle(Action<IQJob> handler) { DetailHandler = handler; return this; } /// <summary> /// 持久化地址 /// </summary> /// <returns>【例:../job/syscode_name_group_jobid.xml】</returns> public string Path() { return System.IO.Path.Combine(JobFactory.Instance.GetPath(), string.Format("{0}_{1}_{2}_{3}.xml", SysCode, Group, Name, JobId)); } /// <summary> /// 移除任務 /// </summary> /// <returns></returns> public bool Remove() { return JobFactory.Instance.Remove(Key()); } /// <summary> /// 暫停任務 /// </summary> public void Pause() { JobFactory.Instance.Pause(Key()); } /// <summary> /// 繼續執行任務 /// </summary> public void Resume() { JobFactory.Instance.Resume(Key()); } } }
1.建立任務的時候主要有散佈操做:
1.建立jobdetail
2.建立jobtrigger
3.建立jobexcute
2.對任務的操做都會執行相應的靜態變量jobs【list<IMJob>】
3.持久化操做包操做數據保存到xml中
using Quartz; using Quartz.Impl; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Quartz { /// <summary> /// quartz.net接任務調度口實現 /// 做者:王延領 /// 時間:2016/5/5 /// </summary> public class JobFactory : IJobFactory { /// <summary> /// 單例模式 /// </summary> private static JobFactory _Instance = new JobFactory(); public static JobFactory Instance { get { return _Instance; } } public JobFactory() { ssf = new StdSchedulerFactory(); _scheduler = ssf.GetScheduler(); } ISchedulerFactory ssf; IScheduler _scheduler; /// <summary> /// 任務持久化文件保存地址 /// 注:默認保存在@"..\..\jobs\"文件夾下 /// 直接地址結尾加"\" /// </summary> private string _path { get; set; } public void SetPath(string path) { _path = path; } public string GetPath() { if (string.IsNullOrEmpty(_path)) _path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory.ToString(), @"..\..\jobs\"); return _path; } //<summary> //建立任務 //</summary> //<param name="myjob">任務對象</param> public string Build(IQJob qjob) { IMyJob myjob = new MyJob(qjob); if (JobVariables.jobs.Exists(j => j.JobId == myjob.JobId && j.SysCode == myjob.SysCode)) return "任務與存在!!!"; JobAdd(myjob); IJobDetail jobdetail = Create_Jobdetail(myjob); ISimpleTrigger trigger = Create_Trigger(myjob); _scheduler.ScheduleJob(jobdetail, trigger); if (_scheduler.IsShutdown || _scheduler.InStandbyMode) _scheduler.Start(); StandSave(qjob); return qjob.Key(); } /// <summary> /// 建立jobdetail /// </summary> /// <param name="qjob"> /// 默認執行Create_Execute /// </param> /// <returns></returns> protected IJobDetail Create_Jobdetail(IMyJob qjob) { IJobDetail jobdetail = JobBuilder.Create<Create_Job>() .WithIdentity(qjob.JobId, qjob.SysCode) .Build(); return jobdetail; } /// <summary> /// 建立job觸發器 /// </summary> /// <param name="qjob"></param> /// <returns></returns> protected ISimpleTrigger Create_Trigger(IMyJob qjob) { ISimpleTrigger trigger; trigger = (ISimpleTrigger)TriggerBuilder.Create().WithIdentity(qjob.JobId, qjob.SysCode) .StartAt(qjob.StartTime).WithSimpleSchedule(x => x.WithIntervalInSeconds(qjob.Seconds) .WithRepeatCount(qjob.MaxTimes - 1)) .Build(); return trigger; } /// <summary> /// 建立任務執行 /// </summary> public class Create_Job : IJob { public void Execute(Quartz.IJobExecutionContext context) { IMyJob myjob = JobFactory.Instance.Find(context.JobDetail.Key); if (myjob.State != JobState.Working) return; JobFactory.Instance.JobRemove(myjob); myjob.Excute(); JobFactory.Instance.JobAdd(myjob); } } /// <summary> /// 從任務列表中刪除指定對象 /// </summary> /// <param name="myjob"></param> /// <returns></returns> bool JobRemove(IMyJob myjob) { return JobVariables.jobs.Remove(myjob); } /// <summary> /// 向任務列表中添加指定對象 /// </summary> /// <param name="myjob"></param> void JobAdd(IMyJob myjob) { JobVariables.jobs.Insert(0, myjob); } /// <summary> /// 獲取MyJob /// </summary> /// <param name="jobkey">JobDetail.JobKey</param> /// <returns></returns> IMyJob Find(JobKey jobkey) { return JobVariables.jobs.SingleOrDefault(j => j.JobId == jobkey.Name && j.SysCode == jobkey.Group); } /// <summary> /// 獲取任務 /// </summary> /// <param name="jobkey">IMyJob.Key()</param> /// <returns></returns> public IMyJob FindByKey(string jobkey) { var job = JobVariables.jobs.SingleOrDefault(j => j.Key() == jobkey); return job; } /// <summary> /// 初始化任務 /// </summary> public void Initialize() { string[] array = XMLProcess.GetFiles(); if (array == null) return; foreach (var path in array) { IQJob myjob = XMLProcess.Deserialize(typeof(QJob), XMLProcess.ReadXml(path)) as QJob; IMyJob qjob = new MyJob(myjob); JobFactory.Instance.Build(myjob); DateTime nowtime = Convert.ToDateTime(string.Format("{0}:{1}", DateTime.Now.Hour, DateTime.Now.Minute)); DateTime jobtime = Convert.ToDateTime(string.Format("{0}:{1}", myjob.StartTime.Hour, qjob.StartTime.Minute)); if (DateTime.Compare(nowtime, Convert.ToDateTime(jobtime)) > 0) DoJob(qjob); } } /// <summary> /// 當即執行job /// </summary> /// <param name="job"></param> void DoJob(IMyJob myjob) { try { JobRemove(myjob); if (myjob.State != JobState.Working) return; //獲取訂閱委託列表 myjob.Excute(); JobAdd(myjob); } catch (Exception ex) { } } /// <summary> /// 任務持久保存 /// </summary> /// <param name="job"></param> protected void StandSave(IQJob job) { job.State = JobState.Working; job.Action = JobAction.NewOne; string xml = XMLProcess.Serializer(typeof(QJob), job); XMLProcess.Write(xml, job.Path()); } /// <summary> /// 獲取全部任務 /// </summary> /// <returns></returns> public List<IMyJob> FindAll() { return JobVariables.jobs; } /// <summary> /// 刪除任務 /// </summary> /// <param name="jobkey">IMyJob.Key()</param> /// <returns></returns> public bool Remove(string jobkey) { var myjob = FindByKey(jobkey); ; if (myjob == null) return false; return JobsRemove(myjob); } /// <summary> /// 刪除任務 /// </summary> /// <param name="syscode"></param> public void RemoveAll(string syscode) { for (int i = JobVariables.jobs.Count - 1; i >= 0; i--) { if (JobVariables.jobs[i].SysCode == syscode) JobsRemove(JobVariables.jobs[i]); } } /// <summary> /// 移除任務 /// </summary> /// <param name="myjob">IQjob</param> /// <returns></returns> bool JobsRemove(IMyJob myjob) { try { bool flag = _scheduler.DeleteJob(new JobKey(myjob.JobId, myjob.SysCode)); if (flag) { JobRemove(myjob); myjob.QRemove(); } return flag; } catch (Exception ex) { return false; } } /// <summary> /// 暫停任務 /// </summary> /// <param name="jobkey">IMyJob.Key()</param> /// <returns></returns> public bool Pause(string jobkey) { try { var myjob = FindByKey(jobkey); ; if (myjob == null) return false; return JobsPause(myjob); } catch (Exception ex) { return false; } } /// <summary> /// 暫停任務 /// </summary> /// <param name="syscode">系統編碼</param> public void PauseAll(string syscode) { for (int i = JobVariables.jobs.Count - 1; i >= 0; i--) { if (JobVariables.jobs[i].SysCode == syscode) JobsPause(JobVariables.jobs[i]); } } /// <summary> /// 暫停任務 /// </summary> /// <param name="myjob"></param> /// <returns></returns> bool JobsPause(IMyJob myjob) { try { _scheduler.PauseJob(new JobKey(myjob.JobId, myjob.SysCode)); JobRemove(myjob); myjob.QPause(); JobAdd(myjob); return true; } catch (Exception ex) { return false; } } /// <summary> /// 繼續任務 /// </summary> /// <param name="jobkey">IMyJob.Key()</param> public bool Resume(string jobkey) { var myjob = FindByKey(jobkey); ; if (myjob == null) return false; return JobsResume(myjob); } /// <summary> /// 繼續任務 /// </summary> /// <param name="syscode">系統編碼</param> public void ResumeAll(string syscode) { for (int i = JobVariables.jobs.Count - 1; i >= 0; i--) { if (JobVariables.jobs[i].SysCode == syscode) JobsResume(JobVariables.jobs[i]); } } bool JobsResume(IMyJob myjob) { try { _scheduler.ResumeJob(new JobKey(myjob.JobId, myjob.SysCode)); JobRemove(myjob); myjob.QResume(); JobAdd(myjob); return true; } catch (Exception ex) { return false; } } /// <summary> /// 任務是否存在 /// </summary> /// <param name="jobkey">IMyJob.Key()</param> /// <returns></returns> public bool Exists(string jobkey) { return JobVariables.jobs.Exists(j => j.Key() == jobkey); } /// <summary> /// 任務狀態 /// </summary> /// <param name="jobkey">IMyJob.Key()</param> /// <returns></returns> public JobState State(string jobkey) { var myjob = FindByKey(jobkey); if (myjob == null) return JobState.Empty; return myjob.State; } /// <summary> /// 獲取任務數量 /// </summary> /// <returns>全部任務數量</returns> public int JobCount() { return JobVariables.jobs.Count; } /// <summary> /// 獲取任務數量 /// </summary> /// <param name="syscode">系統編碼</param> /// <param name="state">任務狀態</param> /// <returns>指定任務數量</returns> public int JobCount(string syscode, JobState state) { return JobVariables.jobs.FindAll(j => j.State == state && j.SysCode == syscode).Count; } public void Trigger(string systme_code, Action<IQJob> action) { var sh = JobVariables.GetHandlers.SingleOrDefault(h => h.systme_code == systme_code); if (sh == null) sh = new JobExcuteHandler() { systme_code = systme_code }; JobVariables.GetHandlers.Remove(sh); sh.detailexcute = action; JobVariables.GetHandlers.Add(sh); } public void Trigger(string systme_code, Action action) { var sh = JobVariables.GetHandlers.SingleOrDefault(h => h.systme_code == systme_code); if (sh == null) sh = new JobExcuteHandler() { systme_code = systme_code }; JobVariables.GetHandlers.Remove(sh); sh.excute = action; JobVariables.GetHandlers.Add(sh); } } }
包括三部分數據:
1.任務的相關的枚舉【狀態,和動做】
2.任務列表
3.觸發動做列表
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Quartz { /// <summary> /// 任務狀態 /// </summary> public enum JobState { Working = 0, Pending = 1, Empty = 2 } /// <summary> /// 任務動做 /// </summary> public enum JobAction { NewOne = 0, Excute = 1, Delete = 2, Pend = 3, Resume = 4 } public class JobVariables { /// <summary> /// 任務調度集合 /// </summary> private static List<IMyJob> _jobs = new List<IMyJob>(); public static List<IMyJob> jobs { get { return _jobs; } } /// <summary> /// 任務觸發動做集合 /// </summary> private static List<JobExcuteHandler> _excutehandlers = new List<JobExcuteHandler>(); public static List<JobExcuteHandler> GetHandlers { get { return _excutehandlers; } } } public class JobExcuteHandler { public string systme_code { get; set; } public Action<IQJob> detailexcute { get; set; } public Action excute { get; set; } } }
主要包括xml的序列化和反序列化操做
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; namespace Quartz { public class XMLProcess { public XMLProcess() { } public XMLProcess(string strpath) { this._xmlpath = strpath; } private string _xmlpath; public string XMLPath { get { return this._xmlpath; } } /// <summary> /// 導入XML文件 /// </summary> /// <param name="XMLPath">XML文件路徑</param> private XmlDocument XMLLoad() { string XMLFile = XMLPath; XmlDocument xmldoc = new XmlDocument(); try { string filename = AppDomain.CurrentDomain.BaseDirectory.ToString() + XMLFile; if (File.Exists(filename)) xmldoc.Load(filename); } catch (Exception e) { } return xmldoc; } public static string ReadXml(string path) { XmlDocument xd = new XmlDocument(); xd.Load(path); return xd.InnerXml; } /// <summary> /// 獲取指定文件夾下的xml文件物理地址 /// </summary> /// <param name="path">文件路徑</param> /// <returns>物理地址數組</returns> public static string[] GetFiles() { try { string pathname = JobFactory.Instance.GetPath(); if (Directory.Exists(pathname)) return Directory.GetFiles(pathname, "*.xml"); return null; } catch (Exception ex) { return null; } } /// <summary> /// 把xml字符串轉爲xml文件 /// </summary> /// <param name="strxml">xml字符串</param> /// <param name="filename">文件名稱xml格式</param> ///<param name="path">保存的物理地址【默認:\bin\..\..\jobs\】</param> public static void Write(string strxml, string filefullname) { try { var path = JobFactory.Instance.GetPath(); if (!Directory.Exists(path)) Directory.CreateDirectory(path); //if (File.Exists(pathname + filename) && filename.ToLower().EndsWith(".xml")) return; using (StreamWriter sw = new StreamWriter(filefullname, false)) { sw.Write(strxml); sw.Close(); } } catch (Exception ex) { } } /// <summary> /// 刪除文件 /// </summary> /// <param name="filefullpath"></param> public static void Delete(string filefullpath) { System.IO.File.Delete(filefullpath); } /// <summary> /// 反序列化 /// </summary> /// <param name="type">類型</param> /// <param name="xml">XML字符串</param> /// <returns></returns> public static object Deserialize(Type type, string xml) { try { using (StringReader sr = new StringReader(xml)) { XmlSerializer xmldes = new XmlSerializer(type); return xmldes.Deserialize(sr); } } catch (Exception e) { return null; } } /// <summary> /// 反序列化 /// </summary> /// <param name="type">類型</param> /// <param name="xml">XML字符串</param> /// <returns></returns> public static T Deserialize<T>(string xml) where T : class,new() { try { using (StringReader sr = new StringReader(xml)) { XmlSerializer xmldes = new XmlSerializer(typeof(T)); return xmldes.Deserialize(sr) as T; } } catch (Exception e) { return default(T); } } /// <summary> /// 序列化 /// </summary> /// <param name="type">類型</param> /// <param name="obj">對象</param> /// <returns></returns> public static string Serializer(Type type, object obj) { string XMLSTR = string.Empty; MemoryStream Stream = new MemoryStream(); XmlSerializer xml = new XmlSerializer(type); try { //序列化對象 xml.Serialize(Stream, obj); XMLSTR = Encoding.UTF8.GetString(Stream.ToArray()); } catch (InvalidOperationException) { throw; } Stream.Dispose(); return XMLSTR; } } }
測試案例不是特別的全。
public class MyJobTests { private static MyJobTests _Instance = new MyJobTests(); public static MyJobTests Instance { get { return _Instance; } } public void JobHandler() { Console.WriteLine("job:當即執行每一個2s執行一次,執行5次"); } public void Job1() { Console.WriteLine("job1:每隔2s執行,執行5次"); } public void Job2() { Console.WriteLine("job2:與job 1syscode相同,每隔2s執行,執行5次"); } public void Job3() { Console.WriteLine("job3,每隔2s執行,執行5次"); } public void Job4() { Console.WriteLine("job4 :與job3 jobid相同,每隔2s執行一次,執行5次"); } public void job5() { Console.WriteLine("兩個job5 : jobid,syscode都相同, 每隔2s執行一次,執行5次"); } public void JobDetailHandler(IQJob job) { Console.WriteLine("系統啓動40s後,無限次執行,須要參數的動做" + job.Times + "_" + job.Action + "_" + job.State); } public void JobPending() { Console.WriteLine("jobpending:當即執行,沒2s執行1次,執行10次,用於測試pending,pengding的觸發會在5s後執行。"); } public void JobResume() { Console.WriteLine("jobresume:當即執行,沒2s執行1次,執行5次,pengding的觸發會在5s後執行,5後resume執行"); } public void MyJobSpendingTest() { new QJob("syscodepeng", "jobidpeng", "name", "group").Handle(JobPending).Start(DateTime.Now, 2, 5); Thread.Sleep(5000); new QJob("syscodepeng", "jobidpeng", "name", "group").Pause(); } public void MyJobResumeTest() { new QJob("syscodeResume", "jobid", "name", "group").Handle(JobResume).Start(DateTime.Now, 2, 5); Thread.Sleep(5000); new QJob("syscodeResume", "jobid", "name", "group").Pause(); Thread.Sleep(5000); new QJob("syscodeResume", "jobid", "name", "group").Resume(); } /// <summary> /// 當即執行,每一個2s執行一次,執行5次 /// </summary> public void MyJobsTest() { new QJob("syscode1", "jobid", "name", "group").Handle(JobHandler).Start(DateTime.Now, 2, 5); } public void MyJobsTest1() { new QJob("syscode1", "jobid1", "name", "group").Handle(Job3).Start(DateTime.Now.AddSeconds(5), 2, 5); new QJob("syscode2", "jobid1", "name", "group").Handle(Job4).Start(DateTime.Now.AddSeconds(8), 2, 5); } public void MyJobsTest2() { new QJob("syscode3", "jobid3", "name", "group").Handle(Job1).Start(DateTime.Now.AddSeconds(15), 2, 5); new QJob("syscode3", "jobid4", "name", "group").Handle(Job2).Start(DateTime.Now.AddSeconds(18), 2, 5); } public void MyJobsTest3() { new QJob("syscode5", "jobid5", "name", "group").Handle(job5).Start(DateTime.Now.AddSeconds(30), 2, 5); new QJob("syscode5", "jobid5", "name", "group").Handle(job5).Start(DateTime.Now.AddSeconds(32), 2, 5); } public void MyJobsTest4() { new QJob("syscode6", "jobid6", "name", "group").Handle(JobDetailHandler).Start(DateTime.Now.AddSeconds(40), 2, 0); } public void MyJobInitialize() { int i = JobFactory.Instance.JobCount(); // Console.WriteLine("初始化後任務個數" + i); JobFactory.Instance.SetPath(@"C:\InitializeFILE"); IQJob job = new QJob("SYSCODEiNS", "JOBID"); string xml = XMLProcess.Serializer(typeof(QJob), job); XMLProcess.Write(xml, job.Path()); JobFactory.Instance.Initialize(); i = JobFactory.Instance.JobCount(); JobFactory.Instance.SetPath(""); Console.WriteLine("初始化後任務個數" + i); } }