首页 > 技术文章 > 写一个服务,隔5分钟检测一次,某一个进程,是否启动,如果没有启动,则开启进程

silence-blog 2016-01-26 10:29 原文

 public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            System.Timers.Timer timer1 = new System.Timers.Timer();  //创建一个定时器
            timer1.Interval = 1000 * 60 * 5;//5min执行一次
            timer1.Elapsed += Timer1_Elapsed;
            timer1.Enabled = true;
            timer1.Start();
            string ope = "启动服务";
            SaveRecord(ope);
            StartServer();
        }

        private void Timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            string ope = "启动服务";
            SaveRecord(ope);
            StartServer();
        }

        private void StartServer()
        {
            Process[] processes = Process.GetProcessesByName("iexplore");  //进程名称


            if (processes == null || processes.Length == 0)
            {
                Process myProcess = new Process();
                try
                {
                    myProcess.StartInfo.UseShellExecute = false;  //是否使用操作系统shell启动进程
                    myProcess.StartInfo.FileName = "C:\\Program Files\\Internet Explorer\\iexplore.exe";  //进程路径
                    myProcess.StartInfo.CreateNoWindow = true;   //是否在新窗口中,启动该进程的值
                    myProcess.Start(); //启动process组件的Process.StartInfo属性的指定进程资源
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }

        private void SaveRecord(string ope)
        {
            using (FileStream fs = new FileStream("E:\\log.txt", FileMode.Append, FileAccess.Write))
            {
                using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
                {
                    sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ope);
                }
            }
        }

        protected override void OnStop()
        {
            string ope = "停止服务";
            SaveRecord(ope);
        }
    }

创建写完之后,需要将服务安装到计算机。

安装服务最简单的方法:

1.将c:\\window\microsoft .net\……4.5(3.5,4.0)下面的InstallUtil.exe 与InstallUtilLib.dll复制到服务项目bin\debug目录下

2.新建一个Txt文件,输入InstallUtil (-e) WindowsService1.exe  另存为install.bat,然后双击此文件,即可安装服务。

3.1输入services.msc查看服务,找到刚刚安装的服务,启动就可以了。

3.2或者在cmd下,输入net start 服务名称。如:net start Service1

卸载服务最简单的方法: (卸载之前最好先将服务停止net stop Service1)

1.将c:\\window\microsoft .net\……4.5(3.5,4.0)下面的InstallUtil.exe 与InstallUtilLib.dll复制到服务项目bin\debug目录下

2.新建一个Txt文件,输入InstallUtil -u WindowsService1.exe  另存为uninstall.bat,然后双击此文件,即可卸载服务。

3输入services.msc查看服务,可以看到卸载的服务已经没有了。

安装与卸载服务,也可以写到c#程序中:


写到C#程序中后,直接运行.exe文件就ok了。

class Program
    {
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            string sysDisk = System.Environment.SystemDirectory.Substring(0, 3);
            string dotNetPath = sysDisk + @"Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe"; //.net4.0的环境
            string serviceExePath = Application.StartupPath + @"\WindowsService1.exe";//exe文件的路径,将服务的exe文件放到此项目的bin下

            string serviceInstallCommand = string.Format(@"{0} {1}", dotNetPath, serviceExePath);  //安装服务时使用的dos命令

            string serviceUninstallCommand = string.Format(@"{0} -u {1}", dotNetPath, serviceExePath);//卸载服务时使用的dos命令
            try
            {
                if (File.Exists(dotNetPath))
                {
                    string[] cmd = new string[] { serviceUninstallCommand, "net stop Service1" };
                    string ss = Cmd(cmd);
                    CloseProcess("cmd.exe");
                }
            }
            catch
            { }
            Thread.Sleep(1000);


            try
            {
                if (File.Exists(dotNetPath))
                {
                    string[] cmd = new string[] { serviceInstallCommand };//{serviceInstallCommand,"net start Service1"}  在cmd中直接启动也可以
                    string ss = Cmd(cmd);
                    CloseProcess("cmd.exe");
                }
            }
            catch
            { }

            try
            {
                Thread.Sleep(3000);
                ServiceController sc = new ServiceController("Service1");

                //判断服务的当前状态,如果没有启动,则启动。
                if (sc != null && (sc.Status.Equals(ServiceControllerStatus.Stopped)) || (sc.Status.Equals(ServiceControllerStatus.StopPending)))
                {
                    sc.Start();
                }
                sc.Refresh();
            }
            catch (Exception e) { Console.WriteLine(e.Message); }
        }

        private static bool CloseProcess(string procName)
        {
            bool result = false;
            System.Collections.ArrayList procList = new System.Collections.ArrayList();
            string tempName = "";
            int begpos;
            int endpos;
            foreach (Process item in Process.GetProcesses())
            {
                tempName = item.ToString();
                begpos = tempName.IndexOf("(") + 1;
                endpos = tempName.IndexOf(")");
                tempName = tempName.Substring(begpos, endpos - begpos);
                procList.Add(tempName);

                if (tempName == procName)
                {
                    if (!item.CloseMainWindow())
                        item.Kill();//当发送关闭窗口命令无效时强行结束进程
                    return true;
                }
            }
            return result;
        }

        private static string Cmd(string[] cmd)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            p.StandardInput.AutoFlush = true;
            for (int i = 0; i < cmd.Length; i++)
            {
                p.StandardInput.WriteLine(cmd[i].ToString());
            }
            p.StandardInput.WriteLine("exit");
            string strRst = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
            p.Close();
            return strRst;
        }
    }

 

推荐阅读