2016-09-28 76 views
-1

如何创建一个函数以在上午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(); 
    } 
} 
+0

http://stackoverflow.com/questions/4529019/how-to-use-the-net-timer-class-to-trigger-an-event-at-特定时间 –

+2

您需要一个调度程序。用自己的计时器写一个支票或使用Quartz.net等第三方调度程序。 –

+0

窗口调度器怎么样? –

回答

1

这是代码做假设您想要关闭的应用程序@ 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); 
     } 
+0

它将与.Net版本3.5一起使用吗? –

+0

我可以为结束时间提出一个不同的计算,结束于上午6:00? 'var endTime = DateTime.Now.Hour <6? DateTime.Today.AddHours(6):DateTime.Today.AddDays(1).AddHours(6);'同时处理当前时间在6:00之前,当前时间在6:00之后 - 结束下一个天。 – grek40

+0

@ grek40如果现在是凌晨2:00,那么你的代码将导致上午8:00不是上午6:00,如果时间是上午8:00,那么它将是下午2:00的第二天,这是错误的在这两种情况下 –

2

这段代码应该工作。 不要忘记添加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(); 
    } 
+0

我应该在哪里放置foreach代码?在Console.WriteLine之上(“等待”);? –

+0

首先调用CloseAt()方法,然后执行你的foreach代码 –

+0

为什么它没有停止..当我测试它。我设置了CloseAt(新的TimeSpan(18,57,0)); –

相关问题