【发布时间】:2015-09-02 15:07:26
【问题描述】:
所以我尝试修改 Sriram Sakthivel 在这里发布的代码块:
C#: How to start a thread at a specific time
public class Program
{
static Boolean checkIn = false;
public static void checkInCycle()
{
checkIn = SynchronousSocketClient.StartClient();
if(checkIn == false)
{
// Use TimeSpan constructor to specify:
// ... Days, hours, minutes, seconds, milliseconds.
TimeSpan span = new TimeSpan(00, 00, 30);
//SetUpTimer(span);
DateTime current = DateTime.Now;
TimeSpan triggerTime = current.TimeOfDay + span;
SetUpTimer(triggerTime);
}
if(checkIn == true)
{
//Do some processing
}
}
public static void SetUpTimer(TimeSpan alertTime)
{
//DateTime current = DateTime.Now;
//TimeSpan timeToGo = alertTime - current.TimeOfDay;
TimeSpan timeToGo = alertTime;
Console.WriteLine("Checking in at: " + timeToGo);
if (timeToGo < TimeSpan.Zero)
{
return; //time already passed
}
System.Threading.Timer timer = new System.Threading.Timer(x =>
{
Console.WriteLine("Running CheckIn Cycle");
checkInCycle();
}, null, timeToGo, Timeout.InfiniteTimeSpan);
}
public static int Main(String[] args)
{
checkInCycle();
Console.WriteLine("End of Program Reached");
Console.ReadLine();
return 0;
}
}
但是,我没有指定确切的运行时间,而是尝试在当前时间上增加 30 分钟,以尝试使客户端服务在尝试再次连接之前保持活动 x 分钟。现在,为了简单/测试起见,如果它无法连接到服务器,我将其设置为每 30 秒运行一次 checkInCycle。
首先检查 SynchronousSocketClient.StartClient();如果服务器关闭,则成功返回 false,并将进入 if(checkIn == false) 循环 - 但是,在设置计时器后,它会继续处理主循环的其余部分,并在结束时等待而不触发和重新调度计时器。
关于为什么会发生这种情况的任何想法?另外我知道我可以在再次检查之前让主线程睡眠 x 分钟,但是客户端可能会睡几个小时,因此我听说计时器效率更高,是这样吗?
【问题讨论】:
-
你的计时器可能正在被垃圾收集,因为它是一个局部变量,让它成为一个类级别的变量/字段。
-
你的触发时间应该是
span,不要加上一天中的时间。 -
我很抱歉。您需要保留 Timer 的引用以防止它被垃圾收集。我已在原始帖子中更新了我的答案以反映这一变化。
标签: c# multithreading timer