拥有一个动态的定时器循环

时间:2015-10-06 07:47:14

标签: c# multithreading timer

我试图编写一个工具来每隔x分钟对某些事情进行ping操作。我有以下代码创建我的线程并且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
   */
}

2 个答案:

答案 0 :(得分:2)

您可以使用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
}

答案 1 :(得分:0)

一种可能的方法是让线程休眠直到你想要它运行。但是这会导致一些不良影响,比如很多绝对没有任何过程的过程。另外,如果你想要初步结束......它没有进行太多的额外检查就不会工作(例如,如果你现在想要它结束,如果它以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.
    }
}