You can use a System.Threading.Timer
to run some action at a specified interval. This action can be to check the current time and then ensure the hamsters are where they need to be at that time. You only need to set the timer and it's interval (i.e. how often you want it to check on the hamsters) and then it will act like a "loop", so you can just "fire and forget".
See Timer Class for more info.
The code below is an example of one way to do it. For debugging I've used a very small window between when they should be in thier cages and when they should be outside (in cages at the start of each minute for 5 seconds, then outside for 10 seconds, then inside for 5, etc.), but in your "real world" example you would change it to: if (currentTime.Hours >= 7 && currentTime.Hours <= 17)
private static TimeSpan TimeDiff;
public static void Main()
{
// Pretend it's 7:00 when the app is started by storing the time
// difference so it can be subtracted later when comparing times
TimeDiff = DateTime.Now.TimeOfDay - new TimeSpan(7, 0, 0);
var timer = new System.Threading.Timer(
e => UpdateHamsters(), // The method to execute each interval
null,
TimeSpan.Zero, // How long to wait before the first execution
TimeSpan.FromSeconds(1) // How long to wait between intervals
);
}
public static void UpdateHamsters()
{
// Subtract the time differnce to get adjusted time
var currentTime = DateTime.Now.TimeOfDay - TimeDiff;
var timeString = currentTime.ToString(@"hh\:mm\:ss");
// Adjust as necessary for debugging
if ((currentTime.Seconds > 5 && currentTime.Seconds <= 15) ||
(currentTime.Seconds > 20 && currentTime.Seconds <= 30) ||
(currentTime.Seconds > 35 && currentTime.Seconds <= 45) ||
(currentTime.Seconds > 50))
{
// Code to ensure hamsters are outside
Console.WriteLine($"{timeString} - All hamsters are outside.");
}
else
{
// Code to ensure hamsters are in cages
Console.WriteLine($"{timeString} - All hamsters are in cages.");
}
}