I was tasked to append a timer within my working console app to let it close automatically after some time without requiring a user input. My application has function开发者_运维问答s that delete certain data in the database based on some conditions and exits everytime the user inputs 'exit'. Now the requirement is to automatically stop the process even if the deleting of items is not yet done given that the time set to close the application is provided, say 2 hours.
Can someone help me? Thanks.
You can create a System.Timers.Timer
with an interval of TimeSpan.FromHours(2)
and call Environment.Exit()
in its Elapsed
handler.
I don't believe that killing the program is a good idea since you are manipulating data in a database but I think would be the simplest way to do it.
using Timer = System.Threading.Timer;
class Program
{
private static readonly Timer _timer =
new Timer(o => Environment.Exit(0), null, 5000, Timeout.Infinite);
static void Main(string[] args)
{
Console.ReadLine();
}
}
1) create a timer 2) set interval and the elapsed event handler 3) enable the timer for run
when timer triggers in the method hooked to the event just exit the application
If you are deleting data from database then stopping it Abruptly could be catastrophic. So you can implement somthing like this.
- Perform the time consuming operation in a BackGroundWorker
- Implement a Timer as explained in other examples.
- Then when the Tick/Interval Event is raised Request the BackgroundWorker to Cancel the Task.
- In your Do Work code Listen for this Cancel request and stop the deletion process safely(Either the Do Deletion or Don't Perform the it At all)
- Then Use Environment.Exit() to exit out of the program.
Hope it helps
I solved this problem by having an app.config file where there is a value for key="Stoptime". I then added a condition that checks the current time against the set end time. Following is an example solution (for those having the same problem):
public static void Main(string[] args)
{
string stoptime = ConfigurationManager.AppSettings["Stoptime"];
DateTime timeEnd = Convert.ToDateTime(stoptime);
today = DateTime.Now;
Console.WriteLine(today);
for (int i = 0; i < 100000; i++)
{
id.Add(i.ToString());
}
foreach(string item in id)
{
today = DateTime.Now;
if (timeEnd.CompareTo(today) >= 0)
{
Console.CursorLeft = 0;
Console.Write(item + " " + today);
}
else
{
Console.WriteLine();
Console.WriteLine("break.");
break;
}
}
Console.ReadKey();
}
精彩评论