The last three books of the Old Testament (Haggai, Zechariah and Malachi) were all written after the Babylonian captivity was over. This was after Cyrus of Persia had issued his decree, in 539 BC, that the Jews could return to their land, to Judah and Jerusalem, and that they could rebuild their city walls and temple.
It was during this time that Haggai lived and prophesied. He was most likely one of the returning exiles, part of the first wave of Jews who returned to the land of Israel. However, due to strong opposition from enemies of the Jews living in the land, the rebuilding of the temple did not start until later, during the reign of King Darius.