C# Windows 服务与计时器不发送数据

标签 c# mysql timer console-application

我创建了一个 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/

相关文章:

c# - 抽象类可以作为 Controller 操作中的参数吗?

mysql - 无法添加外键约束 - 我检查了几乎所有内容

java - 关于计时器实用程序

ios - SwiftUI-计时器不会在0处停止

java - 如何使用 Timer 类调用方法,做某事,重置计时器,重复?

c# - web应用之间通信,1个SSL证书,其他没有

c# - 删除多对多 Entity Framework

c# - 如何在 Excel 中以编程方式对工作表进行分组(移位选择)

php - 是否使用 utf8 - MySQL 和 PHP 字符编码问题

php - 如何使用 HTML 中的 Jquery 打开链接,从 MySql 和 PHP 获取 URL