項目中有一個需求,即在管理后台設置一個任務的執行時間,程序獲取到后需要交由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; } }
