Personnaly, when I feel like wandering off, i let it go. I stop working even if it has to be for 1 or 2 hours. Once I feel I had enough, I take a huuuge cup of coffee (or energy drink, your choice), then I get back to work.
When I come back to it, I realize that I have a lot to do in a short time (since I did nothing for the past 2 hours), and the caffein is kicking in. That's when I'm the most productive, and how I manage to get things done.