我有一个带有班级计时器的Windows服务。 Elapsed事件调用此Work方法:
protected override void Work()
{
if (!File.Exists(@"C:\Users\Will\Desktop\Developer stuff\junk text files\reusableservicetest.txt"))
File.Create(@"C:\Users\Will\Desktop\Developer stuff\junk text files\reusableservicetest.txt");
File.WriteAllLines(@"C:\Users\Will\Desktop\Developer stuff\junk text files\reusableservicetest.txt",
new[] { DateTime.Now.ToLongTimeString() });
}
正如您所看到的,它只是将日期时间写入txt文件。该服务安装并启动正常,但不会写日期时间。我有时间试图让这个poc工作。它应该是这里常用模式的抽象:在一定间隔内做一些工作。女士们,先生们,你们看到我出错的地方吗? 这是基类:
using System;
using System.ServiceProcess;
using System.Timers;
namespace WF.EMC.AVP.CommonCore.Utilities
{
public abstract class PollingServiceBase : ServiceBase
{
private readonly Timer _timer;
private System.ComponentModel.IContainer components = null;
private string _serviceName;
protected PollingServiceBase(int pollingMinutes, string serviceName)
{
_serviceName = serviceName;
var pollingInterval = new TimeSpan(0, 0, pollingMinutes, 0);
_timer = new Timer(pollingInterval.TotalMilliseconds) {AutoReset = true};
_timer.Elapsed += timer_Elapsed;
}
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
Work();
}
protected override void OnStart(string[] args)
{
_timer.Start();
}
protected override void OnStop()
{
_timer.Stop();
}
protected abstract void Work();
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
public void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.ServiceName = _serviceName;
}
}
}
在这里我们有了孩子:
namespace TestService7
{
public partial class Service1 : PollingServiceBase
{
public Service1(int pollingMinutes = 1, string serviceName = "TestService7")
: base(pollingMinutes, serviceName)
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}
protected override void Work()
{
if (!File.Exists(@"C:\Users\Will\Desktop\Developer stuff\junk text files\reusableservicetest.txt"))
File.Create(@"C:\Users\Will\Desktop\Developer stuff\junk text files\reusableservicetest.txt");
File.WriteAllLines(@"C:\Users\Will\Desktop\Developer stuff\junk text files\reusableservicetest.txt",
new[] { DateTime.Now.ToLongTimeString() });
}
}
}
答案 0 :(得分:3)
您使用空方法覆盖OnStart。所以你的计时器将无法启动。