10 Minutes Timer in C#
I'm Developing a C# Console Application and I Need to Add a Timer That Starts When I Write "Start" and Automatically Stops When Have Passed 10 Minutes. How Can...
I'm developing a C# Console Application and I need to add a timer that starts when I write "start" and automatically stops when have passed 10 minutes. How can I do this using only the "static void Main()"?
I have this:
using System;
using System.Timers;
namespace myScript
{
class Program
{
static void Main()
{
string getInput = Console.ReadLine();
if (getInput == "start")
{
//start timer
}
if (//10 minutes have passed)
{
//do something
}
}
}
}
Thank you!
2 Answers
//start timer
//put this into your if statement
Timer timer = new Timer (1000 * 60 * 10);
timer.Elapsed += delegate (object sender, EventArgs e)
{
//do something
timer.Stop ();
timer.Dispose ();
};
timer.Start ();
Try this, use system.timers not threading. This should start 10minute timer which does something and disposes itself at the end of operation.
using System;
using System.Threading;
static void Main(string[] args)
{
Console.WriteLine("Please type \"start\" and press ENTER");
while (true)
{
var userInput = Console.ReadLine();
if (userInput.Equals("start"))
{
break;
}
Console.WriteLine("Not correct, please try again");
}
var minutes = 10;
Console.WriteLine("Going to sleep for " + minutes + " Minutes...");
Thread.Sleep(1000 * minutes * 60);
Console.WriteLine("Done...");
Console.ReadLine();
}