Files
zszq-trs/Tools/YLPublishTool/Actions/ServiceAction.cs
T
2024-05-09 14:06:26 +08:00

128 lines
3.8 KiB
C#

using System;
using System.ComponentModel;
using System.ServiceProcess;
namespace YLPublishTool.Actions
{
/// <summary>
/// 停止服务
/// </summary>
[Description("停止服务")]
class StopServiceAction : IPublishAction
{
public StopServiceAction()
{
SleepSeconds = 10;
}
public string ServiceName { get; set; }
/// <summary>
/// 等待时间(秒)
/// </summary>
public int SleepSeconds { get; set; }
public void Execute(IPublishContext context)
{
if (string.IsNullOrWhiteSpace(ServiceName))
{
throw new Exception("服务名称不能为空");
}
try
{
using (var sc = new ServiceController { ServiceName = ServiceName })
{
if (sc.Status != ServiceControllerStatus.Stopped)
{
sc.Stop();
context.SetProperty("[服务]" + ServiceName, "1");
context.LogDebug($"停止服务:{ServiceName},等待时间:{SleepSeconds}s");
System.Threading.Thread.Sleep(SleepSeconds * 1000);
}
else
{
context.LogDebug("服务不需要停止,已处于停止状态,服务:" + ServiceName);
}
}
}
catch (Exception ex)
{
context.LogError("停止服务失败", ex);
}
}
public void SetProperty(string name, string value)
{
if (name == "服务名称")
{
ServiceName = value;
}
else if (name == "等待时间" && !string.IsNullOrEmpty(value))
{
int.TryParse(value.Trim().TrimEnd('s'), out int seconds);
if (seconds < 3) seconds = 3;
SleepSeconds = seconds;
}
}
}
/// <summary>
/// 启动服务
/// </summary>
[Description("启动服务")]
class StartServiceAction : IPublishAction
{
public string ServiceName { get; set; }
public bool CheckStart { get; set; }
public void Execute(IPublishContext context)
{
if (string.IsNullOrWhiteSpace(ServiceName))
{
throw new Exception("服务名称不能为空");
}
if (CheckStart && context.GetProperty("[服务]" + ServiceName) == "1")
{
try
{
using (var sc = new ServiceController { ServiceName = ServiceName })
{
if (sc.Status == ServiceControllerStatus.Stopped)
{
sc.Start();
context.LogDebug("启动服务:" + ServiceName);
}
else
{
context.LogDebug("启动服务失败,服务不处于停止状态,服务:" + ServiceName);
}
}
}
catch (Exception ex)
{
context.LogError("启动服务失败", ex);
}
}
else
{
context.LogInfo("根据启动条件,不需要启动此服务:" + ServiceName);
}
}
public void SetProperty(string name, string value)
{
if (name == "服务名称")
{
ServiceName = value;
}
else if (name == "启动条件" && value == "此服务被当前进程停止")
{
CheckStart = true;
}
}
}
}