如何創建一個函數以在上午06:00自動關閉程序,無論它是否完成其工作?在.Net 3.5的特定時間關閉控制檯應用程序
static void Main(string[] args)
{
//How to create a function to check the time and kill the programe
foreach(var job in toDayjobs)
{
runJob();
}
}
如何創建一個函數以在上午06:00自動關閉程序,無論它是否完成其工作?在.Net 3.5的特定時間關閉控制檯應用程序
static void Main(string[] args)
{
//How to create a function to check the time and kill the programe
foreach(var job in toDayjobs)
{
runJob();
}
}
這是代碼做假設您想要關閉的應用程序@ 6:00 PM
private static bool isCompleted = false;
static void Main(string[] args)
{
var hour = 16;
var date = DateTime.Now;
if (DateTime.Now.Hour > hour)
date = DateTime.Now.AddDays(1);
var day = date.Day;
var timeToShutdown = new DateTime(date.Year, date.Month, day, 18, 0, 0).Subtract(DateTime.Now);
var timer = new System.Timers.Timer();
timer.Elapsed += Timer_Elapsed;
timer.Interval = timeToShutdown.TotalMilliseconds;
timer.Start();
//Do the forloop here
isCompleted= true;
Console.WriteLine("Press any key to continue");
Console.Read();
}
private static void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
var timer = (sender as System.Timers.Timer);
timer.Stop();
timer.Dispose();
if(isCompleted == false)
throw new Exception("Work was not completed");
Environment.Exit(0);
}
它將與.Net版本3.5一起使用嗎? –
我可以爲結束時間提出一個不同的計算,結束於上午6:00? 'var endTime = DateTime.Now.Hour <6? DateTime.Today.AddHours(6):DateTime.Today.AddDays(1).AddHours(6);'同時處理當前時間在6:00之前,當前時間在6:00之後 - 結束下一個天。 – grek40
@ grek40如果現在是凌晨2:00,那麼你的代碼將導致上午8:00不是上午6:00,如果時間是上午8:00,那麼它將是下午2:00的第二天,這是錯誤的在這兩種情況下 –
這段代碼應該工作。 不要忘記添加using System.Threading;
static void Main(string[] args)
{
CloseAt(new TimeSpan(6, 0, 0)); //6 AM
//Your foreach code here
Console.WriteLine("Waiting");
Console.ReadLine();
}
public static void CloseAt(TimeSpan activationTime)
{
Thread stopThread = new Thread(delegate()
{
TimeSpan day = new TimeSpan(24, 00, 00); // 24 hours in a day.
TimeSpan now = TimeSpan.Parse(DateTime.Now.ToString("HH:mm")); // The current time in 24 hour format
TimeSpan timeLeftUntilFirstRun = ((day - now) + activationTime);
if (timeLeftUntilFirstRun.TotalHours > 24)
timeLeftUntilFirstRun -= new TimeSpan(24, 0, 0);
Thread.Sleep((int)timeLeftUntilFirstRun.TotalMilliseconds);
Environment.Exit(0);
})
{ IsBackground = true };
stopThread.Start();
}
我應該在哪裏放置foreach代碼?在Console.WriteLine之上(「等待」);? –
首先調用CloseAt()方法,然後執行你的foreach代碼 –
爲什麼它沒有停止..當我測試它。我設置了CloseAt(新的TimeSpan(18,57,0)); –
http://stackoverflow.com/questions/4529019/how-to-use-the-net-timer-class-to-trigger-an-event-at-特定時間 –
您需要一個調度程序。用自己的計時器寫一個支票或使用Quartz.net等第三方調度程序。 –
窗口調度器怎麼樣? –