[英]Having a dynamic loop of timers
我正在嘗試編寫一種工具,以便每隔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
*/
}
您可以使用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.
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.