The real Moody is well-known for carrying around a hip flask, and only drinking from it, as to avoid being poisoned. Presumably he will drink from it whenever he wants. Barty Crouch Jr. knew this, and used the hip flask to carry around his Polyjuice Potion, as we see at the end of The Goblet of Fire, when Dumbledore pours out the flask onto the floor. So he would have taken a drink in the middle of class, which would have prevented his un-transformation. That way, he also doesn't change back to Barty and then change to Moody, so he avoids the pain.
Then he picked up the hip flask that stood on the desk, unscrewed it, and turned it over. A thick glutinous liquid splattered onto the office floor.
"Polyjuice Potion, Harry," said Dumbledore. "You see the simplicity of it, and the brilliance. For Moody never does drink except from his hip flask, he's well known for it. The imposter needed, of course, to keep the real Moody close by, so that he could continue making the potion. You see his hair..."
-The Goblet of Fire, Chapter 35 - Veritaserum