如何在特定时间启动线程?



我想让程序在早上6:40开始,但是它在开始时几秒钟就关闭了。

void setUpTimer(TimeSpan alertTime)
{
setUpTimer(new TimeSpan(21, 27, 0));
DateTime current = DateTime.Now;
TimeSpan timeToGo = alertTime - current.TimeOfDay;
if (timeToGo < TimeSpan.Zero)
{
return; // Time already passed
}
timer = new System.Threading.Timer(x =>
{
doDiagnosis(); // 
}, null, timeToGo, Timeout.InfiniteTimeSpan);
}

Dodiagnosis是韩国学校的自我诊断自动化方法。与硒

void doDiagnosis()
{
firefoxDriver.Navigate().GoToUrl("https://hcs.eduro.go.kr/");
firefoxDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(1);
var element = firefoxDriver.FindElementByXPath("//[@id='btnConfirm2']");
element.Click();
Thread.Sleep(3000);
schoolSelect();
login();
password();
conditionCheck();
}

我不认为线程是这个目的的最佳解决方案,考虑使用Cron或像Quartz这样的库。NET,它允许调度"作业";在特定的时间运行

我的猜测是应用程序在计时器结束之前退出,然后显然不会触发它。

如果你有一个控制台应用程序,使用Async main应该是相当简单的,并使用像这样的东西:

await Task.Delay(timeToGo);
doDiagnosis(); 

应该防止应用程序在事件被处理之前退出。但这是假设您想要一个只运行一次的应用程序。如果你需要每天运行这个程序,你可以把上面的代码放在一个循环中,但是最好使用windows任务调度程序来调度你的应用程序的运行。

最新更新