using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.Text; using System.Threading; using System.Windows.Forms; namespace MAutoUpdate { public class EAPClock { //EAP小程序的名称,可能是下面两个中的某一个 string eapName1 = AppDomain.CurrentDomain.BaseDirectory + "/EapForIdle.exe"; string eapProcessName = "EapForIdle"; string thisProgramProcessName = "MAutoUpdate"; int thisProgramRunCount = 0; //判本此程序后台是否已运行。1表示没运行,大于1表示后台已运行此程序。 int checkInterval = Convert.ToInt32(ConfigurationManager.AppSettings["RunCheckInterval"]) * 60; bool isStartOrNotEap; //判断EAP小程序是否启动 /// /// 自动定时启动小程序。先判断后台 此程序 是否已运行,如果没运行则调用 newThreadStart() /// public void AutoStartEap() { StartEapForIdle(); StartTimer(); } public void StartTimer() { string errorinfo = string.Empty; System.Timers.Timer timer = new System.Timers.Timer(); timer.Enabled = true; //设置执行一次(false)还是一直执行(true) timer.AutoReset = true; timer.Interval = checkInterval * 1000; timer.Elapsed += delegate { StartEapForIdle(); }; timer.Start(); LogTool.AddLog("**********定时检查任务开启*************"); } /// /// 判断此程序是否单例运行 /// /// 返回值thisProgramRunCount如果大于1,表示小程序已运行。如果等于1,表示只有当前程序在运行。 public int IsOrNontOnlyOneThis() { //通过进程名获取当前进 此程序EAP 运行的实例,存放到进程数组中。 Process[] processes = Process.GetProcessesByName(thisProgramProcessName); thisProgramRunCount = processes.Length; return thisProgramRunCount; } public bool IsRunning(string programName) { var processes = Process.GetProcessesByName(programName); if (processes == null || processes.Length == 0) return false; return true; } /// /// 开个新线程启动小程序. /// public void newThreadStart() { Thread thread = new Thread(AlwaysRun); //新线程调用AlwaysRun()死循环方法 thread.IsBackground = true; thread.Start(); } /// /// 循环检查是否已运行小程序,如果后台没运行小程序,就启动小程序。 /// public void AlwaysRun() { int EAPRunCount; while (true) { EAPRunCount = IsOrNotRunEAP(); if (EAPRunCount == 0) { StartEapForIdle(); } // else MessageBox.Show("小程序已在后台开启,无需再次打开"); Thread.Sleep(30000); //当前线程睡眠 } } public void StartEapForIdle() { LogTool.AddLog("**********检查EAP小程序开启状态开始*************"); LogTool.AddLog("小程序路径:" + eapName1); if (!IsRunning(eapProcessName)) { try { Process.Start(eapName1); LogTool.AddLog("**********小程序被关闭,已重新开启*************"); } catch (Exception ex) { LogTool.AddLog("自动重启EAP程序失败,原因为:" + ex.ToString()); } } else { LogTool.AddLog("**********小程序运行中*************"); } LogTool.AddLog("**********检查EAP小程序开启状态结束*************"); } /// /// 判断小程序是否在进程中运行,返回值EAPRunCount如果大于0,表示小程序已运行。如果等于0,表示未运行。 /// public int IsOrNotRunEAP() { //通过小程序进程名获取当前进小程序运行的实例,存放到进程数组中。 Process[] processes = Process.GetProcessesByName(eapProcessName); int EAPRunCount = processes.Length; return EAPRunCount; } } }