C# 時間轉Quartz任務調度器cron表達式


 

項目中有一個需求,即在管理后台設置一個任務的執行時間,程序獲取到后需要交由Quartz任務調度器執行。

由於操作人員不可能寫cron表達式,所以需要將管理后台寫入的時間值轉為相應的cron表達式,在網上搜了下沒找到滿意答案就自己寫了個,希望對別人有用吧。代碼如下:

 
         
        /// <summary>
        /// 時間格式轉換成Quartz任務調度器Cron表達式 /// </summary>
        /// <param name="time">時間值,支持HH:mm:ss | HH:mm</param>
        /// <returns></returns>
        public static string TimeToQuartzCron(string time) { try { if (string.IsNullOrWhiteSpace(time)) return ""; string error = "傳入的時間值[" + time + "]格式有誤!"; int ss = 0, mi = 0, hh = 0; if (time.Length < 5) throw new Exception(error); if (time.Substring(2, 1) != ":") throw new Exception(error); if (!int.TryParse(time.Substring(0, 2), out hh)) throw new Exception(error); if (!int.TryParse(time.Substring(3, 2), out mi)) throw new Exception(error); if (time.Length > 5) { if (time.Substring(5, 1) != ":") throw new Exception(error); if (!int.TryParse(time.Substring(6), out ss)) throw new Exception(error); } if (ss > 59) throw new Exception(error); if (mi > 59) throw new Exception(error); if (hh > 23) throw new Exception(error); string cronValue = ss + " " + mi + " " + hh + " " + "* * ?"; return cronValue; } catch (Exception ea) { throw ea; } }
 
         

 

 
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM