zechosenpessimist
zechosenpessimist
CC#
Created by zechosenpessimist on 10/10/2023 in #help
❔ Timer
time remaining until the end of the timer
29 replies
CC#
Created by zechosenpessimist on 10/10/2023 in #help
❔ Timer
Yes, I'm trying to write an event that triggers when the time on the timer changes
29 replies
CC#
Created by zechosenpessimist on 10/10/2023 in #help
❔ Timer
class Program
{
static void Main()
{
SpecialTimer specialTimer = SpecialTimer.Instance;

specialTimer.TimeLeftChanged += TimeLeftChangedHandler;

specialTimer.AddTime(10);

Console.ReadLine();
}

private static void TimeLeftChangedHandler(int secondsLeft)
{
Console.WriteLine($"Time left: {secondsLeft} seconds");
}

public class SpecialTimer : System.Timers.Timer
{
private static SpecialTimer instance;
private static readonly object lockObject = new object();

public delegate void TimeLeftChangedHandler(int secondsLeft);

public event TimeLeftChangedHandler? TimeLeftChanged;

private SpecialTimer() : base()
{
Elapsed += TimerElapsed;
}

private void TimerElapsed(object sender, ElapsedEventArgs e)
{
Stop();
}

public void AddTime(int seconds)
{
if (Enabled && Interval > 0)
{
Stop();

double newInterval = Interval + seconds * 1000;
Interval = newInterval > 0 ? newInterval : 0;

Start();
}
else
{
instance = new SpecialTimer();
instance.Interval = seconds * 1000;
instance.Start();
}
}

public static SpecialTimer Instance
{
get
{
lock (lockObject)
{
return instance ?? (instance = new SpecialTimer());
}
}
}
}
}
class Program
{
static void Main()
{
SpecialTimer specialTimer = SpecialTimer.Instance;

specialTimer.TimeLeftChanged += TimeLeftChangedHandler;

specialTimer.AddTime(10);

Console.ReadLine();
}

private static void TimeLeftChangedHandler(int secondsLeft)
{
Console.WriteLine($"Time left: {secondsLeft} seconds");
}

public class SpecialTimer : System.Timers.Timer
{
private static SpecialTimer instance;
private static readonly object lockObject = new object();

public delegate void TimeLeftChangedHandler(int secondsLeft);

public event TimeLeftChangedHandler? TimeLeftChanged;

private SpecialTimer() : base()
{
Elapsed += TimerElapsed;
}

private void TimerElapsed(object sender, ElapsedEventArgs e)
{
Stop();
}

public void AddTime(int seconds)
{
if (Enabled && Interval > 0)
{
Stop();

double newInterval = Interval + seconds * 1000;
Interval = newInterval > 0 ? newInterval : 0;

Start();
}
else
{
instance = new SpecialTimer();
instance.Interval = seconds * 1000;
instance.Start();
}
}

public static SpecialTimer Instance
{
get
{
lock (lockObject)
{
return instance ?? (instance = new SpecialTimer());
}
}
}
}
}
29 replies