我创建了一个 Windows 服务,使用 json 字符串将性能数据发布到 mySQL 数据库。然而,该服务需要每分钟发布一次数据。我添加了一个计时器,但它似乎并没有每分钟将数据发送到数据库。
我的项目中有 2 个类(class)。 程序类启动服务并运行性能代码。
public static string ServiceName = "performanceService";
static void Main(string[] args)
{
if (!Environment.UserInteractive)
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new ServiceControl()
};
ServiceBase.Run(ServicesToRun);
}
else
{
PerformanceCounter ramCount = new PerformanceCounter("Memory", "Available MBytes");
PerformanceCounter cpuCount = new PerformanceCounter("Processor", "% Processor Time", "_Total");
}
省略其余代码。
然后我有一个ServiceControl类,它实际上是一个Windows服务。在这个类上,我设置了计时器。
System.Timers.Timer timer = new System.Timers.Timer();
public ServiceControl()
{
ServiceName = Program.ServiceName;
InitializeComponent();
}
public void timerElapsed(object sender, EventArgs e)
{
Console.WriteLine("Time Elapsed");
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
timer.Elapsed += new ElapsedEventHandler(timerElapsed);
timer.Interval = 60000;
timer.Enabled = true;
timer.Start();
}
protected override void OnStop()
{
base.OnStop();
timer.Enabled = false;
timer.Stop();
}
private void InitializeComponent()
{
//
// ServiceControl
//
this.ServiceName = "performanceService";
}
如果您想查看任何其他代码,请告诉我。 我的代码中是否存在任何问题,不允许服务按指定的时间间隔发布数据? 谢谢。
最佳答案
我已将计时器放置在 Main(string[] args)
中。这是我的回答:
static void Main(string[] args)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 300000; // 30 minutes
timer.Elapsed += new ElapsedEventHandler(serverCall);
timer.AutoReset = true;
timer.Start();
}
关于C# Windows 服务与计时器不发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34792051/