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

本文关键字:控制台 应用程序 定时间 net | 更新日期: 2023-09-27 18:09:27

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

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

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

假设你想要关闭应用程序@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);
        }