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);
}
}
写一个服务隔5分钟检测一次某一个进程是否启动,如果没有启动,则开启进程 c#
PublishedCreated: 2024年3月24日星期日 11:53:08 views(447)