king yau king yau - 1 year ago 82
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)

Answer Source

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;

 //Do the forloop here
 isCompleted= true;

            Console.WriteLine("Press any key to continue");

        private static void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
            var timer = (sender as System.Timers.Timer);

            if(isCompleted == false)
              throw new Exception("Work was not completed");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download