计时器事件 C#

问题描述

我正在尝试编写一个控制台应用程序,我应该在其中运行仓鼠日托的模拟。任务是让他们到达,把他们关在笼子里,女孩带着女孩,男孩带着男孩。每天有30只仓鼠。我有一个方法可以让他们出去玩,我想每小时调用一次这个方法。我很难让计时器、事件等工作。有人可以帮我开始吗?他们都是每天早上7点到达,所以时间不是DateTime.Now,更像是DateTime.Now.Date.Add(new TimeSpan(7,00,0));为了任务。方法没有问题,但不能让它起作用。

他们应该在 07 点到 17 点,10 小时在日托中心。

var count = DateTime.Now.Date.Add(new TimeSpan(7,0));
        for (int i = 0; i < 100; i++)
        {
          count += TimeSpan.FromMinutes(6);
        }

大家有什么建议吗?或者,如果您需要更多信息,请告诉我!谢谢各位!

解决方法

您可以使用 System.Threading.Timer 以指定的时间间隔运行某些操作。这个动作可以是检查当前时间,然后确保仓鼠在那个时间他们需要去的地方。您只需要设置计时器和它的时间间隔(即您希望它多久检查一次仓鼠),然后它就会像一个“循环”一样运行,这样您就可以“一劳永逸”。

有关详细信息,请参阅 Timer Class

下面的代码是一种方法的示例。为了调试,我在它们应该在笼子里和应该在外面的时间之间使用了一个非常小的窗口(每分钟开始时在笼子里 5 秒,然后在外面 10 秒,然后在里面 5 秒,等等。 ),但在您的“真实世界”示例中,您会将其更改为: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);

    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.");
    }
}
,

啊,好的,感谢您的意见。我一直在尝试这种方法一段时间,但我无法让它发挥作用,或者,我的意思是,它确实有点正确,6 只仓鼠一次出轨,但是当剩下 3 只雄性仓鼠时,那么 3 只雌性仓鼠加入进来。这是我最大的问题。

public static void ThreadLetHamstersPlay()
    {
        lock (hamsterLock)
        {
            using(var db = new HamsterContext())
            {
                int hamstersInExercisearea = 0;
                var availableSpaceInExerciseArea = db.ExerciseArea.Where(EA => EA.AvailableSpace == true).ToList();
                var getHamster = db.Hamsters.Where(H => H.Activity == null).ToList();

                int maxLimit = availableSpaceInExerciseArea.Count <= getHamster.Count ? availableSpaceInExerciseArea.Count : getHamster.Count;

                for (int i = 0; i < maxLimit; i++)
                {
                    if (getHamster[i].Gender == "Male")
                    {
                        getHamster[i].Activity = DateTime.Now;
                        db.SaveChanges();
                        availableSpaceInExerciseArea[i].AvailableSpace = false;
                        getHamster[i].ExerciseAreaID = availableSpaceInExerciseArea[i].ExerciseAreaID;
                        hamstersInExercisearea++;
                        Console.WriteLine($"{getHamster[i].Name} is out playing right now. . . Gender - {getHamster[i].Gender}");
                    }
                    
                    Thread.Sleep(1000);
                    db.SaveChanges();
                }
            }
        }
    }

现在我只检查雄性,如何在雄性完成之前让雌性远离?只是在您输入后稍微更改了方法:)