我正在尝试编写一个工具,用于每一位x分钟来平某些事情。我有下面的代码来创建我的线程,点击也很好,只是我不知道如何在每次线程中动态地制作一个计时器。数据是一个表格,如:
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
*/
}发布于 2015-10-06 08:02:14
您可以使用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
}发布于 2015-10-06 08:04:37
一种可能的方法是让线程休眠,直到您希望它运行为止。但这可能会导致一些不想要的效果,比如许多执行absolutely......nothing的进程。此外,如果您想结束它们,preliminarily......it将无法工作,如果没有相当多的额外检查(例如,如果您希望它现在结束,那么如果它以5000 milliseconds....so结尾,则需要每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.
}
}https://stackoverflow.com/questions/32964446
复制相似问题