【发布时间】:2016-08-18 09:35:59
【问题描述】:
我已经开发了 windows 服务,用于每两分钟检查一些服务是否运行。如果服务没有运行,则自动启动它们。
这是我的代码
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
this.CheckServices();
this.ScheduleService();
}
protected override void OnStop()
{
this.Schedular.Dispose();
}
public void CheckServices()
{
log4net.Config.BasicConfigurator.Configure();
log4net.ILog log = log4net.LogManager.GetLogger(typeof(Service1));
try
{
string[] arr1 = new string[] { "CaseWorksCachingService", "Te.Service" };
for (int i = 0; i < arr1.Length; i++)
{
ServiceController service = new ServiceController(arr1[i]);
service.Refresh();
if (service.Status == ServiceControllerStatus.Stopped)
{
service.Start();
}
}
}
catch (Exception ex)
{
log.Error("Error Message: " + ex.Message.ToString(), ex);
}
}
//ScheduleService Method
private Timer Schedular;
public void ScheduleService()
{
try
{
Schedular = new Timer(new TimerCallback(SchedularCallback));
string mode = ConfigurationManager.AppSettings["Mode"].ToUpper();
//Set the Default Time.
DateTime scheduledTime = DateTime.MinValue;
if (mode.ToUpper() == "INTERVAL")
{
//Get the Interval in Minutes from AppSettings.
int intervalMinutes = Convert.ToInt32(ConfigurationManager.AppSettings["IntervalMinutes"]);
//Set the Scheduled Time by adding the Interval to Current Time.
scheduledTime = DateTime.Now.AddMinutes(intervalMinutes);
if (DateTime.Now > scheduledTime)
{
//If Scheduled Time is passed set Schedule for the next Interval.
scheduledTime = scheduledTime.AddMinutes(intervalMinutes);
}
}
TimeSpan timeSpan = scheduledTime.Subtract(DateTime.Now);
//Get the difference in Minutes between the Scheduled and Current Time.
int dueTime = Convert.ToInt32(timeSpan.TotalMilliseconds);
//Change the Timer's Due Time.
Schedular.Change(dueTime, Timeout.Infinite);
}
catch (Exception ex)
{
//Stop the Windows Service.
using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("MyFirstService"))
{
serviceController.Stop();
}
}
}
private void SchedularCallback(object e)
{
//this.WriteToFile("Simple Service Log: {0}");
this.CheckServices();
this.ScheduleService();
}
}
这是我的 app.config 文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key ="Mode" value ="Interval"/>
<!-- <add key ="Mode" value ="Interval"/>-->
<add key ="IntervalMinutes" value ="2"/>
</appSettings>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=2.0.5, Culture=neutral, PublicKeyToken=1b44e1d426115821" />
</configSections>
<!-- Log4net Logging Setup -->
<log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender,log4net">
<file value="C:\\mylogfile1.txt" />
<!-- the location where the log file would be created -->
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO" />
<levelMax value="FATAL" />
</filter>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="FileAppender" />
</root>
</log4net>
</configuration>
错误:“本地计算机上的 Windows Search 服务启动然后停止。如果某些服务没有被其他服务或程序使用,它们会自动停止”
【问题讨论】:
-
你在
ScheduleService的catch块中停止了服务——好吧,一个服务——没有记录原因。 -
好吧,如果
ScheduleService内部出现问题,您将永远不会发现它,因为您吞下了异常(没有真正的原因,因为未处理的异常无论如何都会导致服务中断,无需您编写任何代码) -
嗨@stuartd,如果调度中出现任何异常,我将停止服务。是不是错了,我不知道是错误。你能建议我在我的代码中哪里做错了吗?
-
嗨@Damien_The_Unbeliever,建议我在我的代码中哪里做错了。
-
我们不知道。你不知道。没人知道。作为第一步,要么在
ScheduleService内的catch内添加一行日志记录,要么(更好)完全删除try/catch块。
标签: c# .net windows-services