I put a pokemon in a gym and the gym later on got defeated and replace with another colour. I didn't get any defender bonus from the gym. This happen two times so far.
You can collect your defender bonus in the shop window of the Pokemon go app.
The bonus can be collected instantly; however, you can only do this while you have your Pokemon in the gym. This means that if you don't collect your bonus while your Pokemon is in the gym and your team controls it you will loose it.
Also (as per comment below by Fatalize); please note that if you collect the defender bonus, and then capture another gym before the bonus claiming has cooled down, you will be unable to claim the bonus for that new gym until the 21 hour cool-down for collection is completed. This means that you may not be able to collect a second bonus at all if you have collected one then join/capture another gym, but loose it before your cool-down for collection is over.
As of the recent gym system overhaul, you no longer collect your gym bonus from the Shop screen. Instead, you are given all of your Defender bonus rewards all at once when your Pokémon that had been defending a gym returns to you. That is, Defender bonus collection is no longer a manual process.
This article explaining the new system backs this up:
But you also do not collect the bonus once every 24 hours anymore. Instead, you only collect it when your Pokemon is no longer defending that gym. Whenever the Pokemon returns to you from the gym, it will bring with it all of the coins that you have collected over that entire period. ... You will receive a notification when the Pokemon returns home from the gym informing you how many coins you have collected.