簡體   English   中英

具有計時器的C#Windows服務不發送數據

[英]C# Windows service with timer not sending data

我做了一個Windows服務,該服務使用json字符串將性能數據發布到mySQL數據庫。 但是,此服務需要每分鍾發布一次數據。 我添加了一個計時器,但是,它似乎並沒有每分鍾將數據發送到數據庫。

我的項目有2個班級。 程序類將啟動服務並運行性能代碼。

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 Service。 在本課程中,我設置了計時器。

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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM