拥有计时器的动态循环

本文关键字:循环 动态 计时器 拥有 | 更新日期: 2023-09-27 18:16:16

我正试图编写一个工具来ping某些事情每x分钟。我有下面的代码创建我的线程和ping是好的,它只是我不能弄清楚如何动态地使一个定时器在我的线程每次。数据是一个表,如:

Id  Name        URL                     Time    Active
1   All good    http://httpstat.us/200  5000    1
2   404         http://httpstat.us/404  2000    1

我的代码如下:(我还没有把变量从循环中放进去)

public void SetupTimers()
{
    DB db = new DB();
    DataTable dtLinks = new DataTable();
    dtLinks = db.GetDataTable(String.Format("SELECT Id, Name, URL, Time, Active FROM Shed WHERE Active = 1"));
    foreach (DataRow row in dtLinks.Rows)
    {
        Thread thread = new Thread(() => SetupShed(1, "WILLBURL", "WILLBENAME"));
        thread.Start();
    }
}

static void SetupShed(Int32 Time, String URL, String Name)
{
   /* Heres where I will do the actual ping 
      but I need to setup a timer to loop every x seconds? 
      It's a contiunous check so it'll have to keep looping over. 
      I've redacted the actual ping for this example
   */
}

拥有计时器的动态循环

您可以使用Timer类。实际上,您不需要创建自己的线程。timer类在幕后为你做这些。

public void SetupTimers()
{
    DB db = new DB();
    DataTable dtLinks = new DataTable();
    dtLinks = db.GetDataTable(String.Format("SELECT Id, Name, URL, Time, Active FROM Shed WHERE Active = 1"));
    foreach (DataRow row in dtLinks.Rows)
    {
        SetupShed(1, "WILLBURL", "WILLBENAME");
    }
}

static void SetupShed(double ms, String url, String name)
{
        System.Timers.Timer timer = new System.Timers.Timer(ms);
        timer.AutoReset = true;
        timer.Elapsed += (sender, e) => Ping(url, name);
        timer.Start();
}
static void Ping(String url, String name)
{
    //do you pinging
}

一种可能的方法是让线程休眠,直到您希望它运行。但是这可能会导致一些不希望的影响,比如许多进程完全......什么都不做。另外,如果您想初步结束它们......如果没有很多额外的检查,它将无法工作(例如,如果您希望它现在结束,如果它在5000毫秒内结束就不好....因此,您需要每隔10-20毫秒检查一次(....)。

采用你最初的方法(注意这里的时间是以毫秒为单位的)。如果你想在秒内完成,那么你需要使用:Thread.Sleep(Time*1000)):

static void SetupShed(Int32 Time, String URL, String Name)
{
   /* Heres where I will do the actual ping 
      but I need to setup a timer to loop every x seconds? 
      It's a contiunous check so it'll have to keep looping over. 
      I've redacted the actual ping for this example
   */
    while (true)
    {
        Thread.Sleep(Time);
        //.....Do my stuff and then loop again.
    }
}