Reputation: 31
I'm attempting to make a "simple" timer from 15 minutes to 0 seconds. I'm using 900 seconds as my 15 minutes. When I Run the program it runs through fine but Continues going into the negatives. I'm still a novice at C#. I'm wanting the code to stop at 0 and run an alert to grab someone's attention. Here is what I have thus far
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
namespace GBS_GI_Timer
{
public class Program
{
public static int t = 2;
public static void Main()
{
System.Timers.Timer aTimer = new System.Timers.Timer();
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 1000;
aTimer.Enabled = true;
//Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine();
//GC.KeepAlive(aTimer);
if (t == 0)
aTimer.Stop();
}
public static void OnTimedEvent(object source, ElapsedEventArgs e)
{
//TimeSpan timeRemaining = TimeSpan.FromSeconds(t);
Console.WriteLine("Time remianing..{0}", t);
t--;
if (t == 0)
{
Console.WriteLine("\a");
Console.WriteLine("Time to check their vitals, again!");
Console.WriteLine("Press any key to exit...");
}
// Console.ReadKey();
Console.ReadLine();
}
}
}
Upvotes: 0
Views: 609
Reputation: 6332
You would have to refactor your code as below to make it work, System.Timers.Timer used ThreadPool to run the callback routines.
class Program
{
public static int t = 2;
static System.Timers.Timer aTimer = new System.Timers.Timer();
public static void Main()
{
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 1000;
aTimer.Enabled = true;
Console.ReadLine();
}
public static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("Time remianing..{0}", t);
t--;
if (t == 0)
{
Console.WriteLine("\a");
Console.WriteLine("Time to check their vitals, again!");
Console.WriteLine("Press any key to exit...");
aTimer.Stop();
Console.ReadLine();
}
}
}
Upvotes: 1
Reputation: 5900
There are some other logic issues with your program as it stands, and I am not certain it would do what you want even if it was running, though.
I would refactor your OnTimedEvent to just do
Console.WriteLine(string.Format("{0} time to check their vitals!"));
and use a while loop to check the status of t in the main routine.
You could also change the Timer.Interval when entering the handler so that no other events fire until they acknowledge the first event, but then you couldn't guarantee that this routine runs for 15 minutes...
Upvotes: 0
Reputation: 2966
You have it coded so that when you hit enter (or type something and hit enter), it then checks t and may stop the timer. You're checking if t == 0 and only then stopping the timer. What happens if t is less than zero before you hit enter?
Upvotes: 3