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