These are questions you might have when seeking a letter of recommendation. Keep in mind that in different situations answers will vary. If you have a specific question about how to move forward, you should approach an advisor, a faculty member, or someone in your advising network. People are eager to help.
When to ask? You should give letter writers at least 3 weeks notice. You are probably asking busy people for letters. They will need to carve time out of their schedule to write a meaningful letter.
If you find out about an opportunity with less than 3 weeks to the deadline, you should still apply. Tell your potential letter writer about the circumstances that have placed you into asking for a letter with such short notice.
Who to ask? You should ask people who are familiar with work of yours that is relevant to the position you are applying. As an undergraduate student the letter should typically come from a TF or a supervisor of yours from previous relevant work experience. Except in exceptional circumstances you do not want to ask a high school teacher or guidance counselor for a letter of recommendation.
You may ask someone who tells you they are too busy to write you a letter. Do not let this dissuade you from seeking other letters. Some people have a certain number of letters they are willing to write and you may just asked at the wrong time.
How to ask? It is helpful for letter writers to have a resume and a cover letter. If the letter writers have some guidance about what the position you are applying for and your interest in the position they are better able to write about your strengths that make you a good fit for the position. A resume helps a letter writer see a more complete picture of you as an applicant.