king yau king yau - 2 months ago 11
C# Question

Close the console application in specific time in .Net 3.5

How to create a function to auto close the programe at 06:00 am no matter does it finished its job or not?

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

Answer

This is the code to do that assuming you want to shut down the app @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);
        }
Comments