在.Net 3.5中的特定时间关闭控制台应用程序

时间:2016-09-28 10:14:20

标签: c#

如何创建一个在06:00 am自动关闭程序的功能,无论它是否完成了它的工作?

 static void Main(string[] args)
 {
    //How to create a function to check the time and kill the programe
    foreach(var job in toDayjobs)
    {          
        runJob();
    }
 }

2 个答案:

答案 0 :(得分: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();
    }

答案 1 :(得分:1)

这是代码,假设你想要关闭应用程序@ 6:00 PM

#true