需求:线上运行的job,有时间可能因为数据库异常、内存不足或者是内部其他异常导致整个进程退出,是偶发事件,但是如果进程停止,业务数据没处理积压起来,会影响业务。为了能自动监控并启动这种意外停止的进程,写了一个程序监控,每分种检查一遍,然后自动处理,实际上是非常有用的。
贴代码如下:
//主要逻辑
var runday = DateTime.Today; ConfigFile.Instanse.fileName = CommonFunctions.GetAbsolutePath("Kulv.YCF.KeepTaskRun.ini");//获取配置文件绝对路径 string ExeFile = ""; string ServiceName = ""; var configIndex = 1; RunTaskAgain(() => { while (true) { try { ExeFile = ConfigFile.Instanse["ExeFile" + configIndex]; if (string.IsNullOrEmpty(ExeFile)) break; Logger.Info("………………………………………………………… ExeFile" + configIndex + " Start……………………………………………………………");//写日志到文本文件中 ServiceName = ConfigFile.Instanse["ServiceName" + configIndex]; var isRun = CommonFunctions.IsProgramRun(ExeFile);//判断exe是否在运行的进程中 if (DateTime.Today != runday) { runday = DateTime.Today; } Logger.Info(string.Format("ExeFile:{0},ServiceName:{1}", ExeFile, ServiceName)); if (isRun) { Logger.Info("程序正在运行中"); } else { Logger.Info(string.Format("程序未运行,尝试启动服务")); var startResult = CommonFunctions.RunCmd(string.Format("sc start "{0}"", ServiceName));//通过cmd命令启动服务 var regex = new Regex("( )+"); startResult = regex.Replace(startResult, "$1");//多个换行替换成一个 Logger.Info(" " + startResult); if (startResult.Contains("失败") == false) { Logger.Info(string.Format("启动服务成功!")); } var phonestr = ConfigFile.Instanse["CellPhone" + configIndex]; FinanceApiInvoke.ApiDomain = ConfigFile.Instanse["MapApiAddress" + configIndex]; ; if (string.IsNullOrEmpty(phonestr)) { Logger.Info(string.Format("短信接收人配置" + configIndex + "为空!")); } else if (string.IsNullOrEmpty(FinanceApiInvoke.ApiDomain)) { Logger.Info(string.Format("短信发送API配置" + configIndex + "为空!")); } else { DateTime dt = DataCache.GetCache<DateTime>("LastSendMsgTime");//用缓存,5分钟内只发一次短信 if ((DateTime.Now - dt).TotalMinutes >= 5) { var phones = phonestr.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); List<SMSForSendIModel> msgList = new List<SMSForSendIModel>(); foreach (var phone in phones) { msgList.Add(new SMSForSendIModel() { CompanyId = CompanyEnum.TestCompany, Phone = phone, SendBy = "KeepTaskRun", UserId = 0, TemplateCode = "NOTICE-COMMON0", UserType = UserType.SystemUser, Content = string.Format("库存服务YCF_STOCK_TASK处于停止状态,监控程序已在尝试启动服务,如果自动启动失败,需要人工处理!如正在发布请忽略此信息。") }); } var sendRet = FinanceApiInvoke.SendSmsToWithEncryptionBatch(msgList, true);//通过api提交要发的短信给内部系统 Logger.InfoFormat("短信返回:{0}", JsonUtility.ToJson(sendRet)); &nbs