Earlier the better... although some may not write you one until your grade is clear to them or the class is over and your grade is final....if that's the case, ask them right after the class finishes.... try to get to know your prof a little bit, it always helps them to write better recs if they know you...good luck!