When a hard fork is scheduled, how does the program recognize the hard fork? And how to make the whole network recognize the new algorithm?
Every hard fork introduces a new version that is programmed to "handle" the fork. Something like "Up until block height XXX do this, starting from block height XXX+1 do that".
Older versions will not be able to do that, because when they were released, no one knew what will the requirements be for the next hard fork. This is the reason that before every hard fork people are being told over and over to update their version.
Every hard fork relies on the hope that most of the network will upgrade to the new version - something that goes pretty well so far.