Invented a task: output a message every minute. This code displays a message, but not once. This should not be, the message should be displayed only once. I really don't understand the mistake.

DateTime fixDate = DateTime.Now; int checkPoint = fixDate.Second; bool key = false; Console.WriteLine($"Секунды при запуске {checkPoint}"); for (; ; ) { DateTime now = DateTime.Now; if ((checkPoint == now.Second) && (key = true)) { Console.WriteLine("Прошла минута"); key = false; } if (checkPoint != now.Second) { key = true; } } 

I am fixing the date, saving myself the second run of the program. I start to constantly update the date, if the second is equal to the checkpoint and the flag is true, then I display the message. The flag is updated and becomes true only if the second is not equal to the checkpoint. From here it is not at all clear how the message can be displayed if the flag can become true only if the second is not equal to the checkpoint. I tried to use debugging, but because of the work with time, the message is never displayed, because the flag is always false. How to properly modify the algorithm so that the message is displayed only once every minute?

  • one
    (key = true) - is it conceived? assign in check? - Zergatul
  • Not a bug but a feature. Extremely grateful - Alexey Fedotov

1 answer 1

  DateTime nextMinute = fixDate.AddMinutes(1); while(true) { DateTime now = DateTime.Now; if (now >= nextMinute) { Console.WriteLine("Прошла минута"); nextMinute = nextMinute.AddMinutes(1); } }