When I battled depression I learned a technique to control my anger that was effective for me. I simply have modified it to help when my mind needs some correction. (START) Stop, Think, Assess, Reassess, Talk is used for anger control. I modified it to (STARR) Stop, Think, Assess, Reassess, Refocus.
I’be trained myself to tell myself to stop when impure thoughts enter my mind. I think about what I should be doing. I assess the situation. I reassess to reassure myself what I need to do, then I refocus on what my mind should be thinking about.
It may seem silly to some, but it works for me.