How far in advance do I need to purchase the tickets?
The Dali Theatre/Museum website lists how many tickets are still available for each time slot you might be interested in.
www.salvador-dali.org
It's a popular place and really busy. If you know when you're going to be there, I would buy them. They definitely sell out. You don't give any details of when you're traveling, how you're getting there etc. so it's hard to say what you should do. But if you're traveling in the next couple of months and you know what day you're going there, I would buy the tickets so you get your chosen time slot.
It was my impression the place didn't sell out very early, but it does get some bus tours, so a lot of tickets could evaporate quite suddenly. I think Kenko's nailed the key bit of info: You can monitor the website to see how tickets are selling.
I'd be really surprised if it's necessary to buy tickets weeks ahead of time. I never do that except for places that are known to sell out regularly. To me, it's a good way to waste money if something happens that derails your itinerary.
However, I do not take rushed trips, so it's very rare for me to need to visit a sight on one specific day. If you have a very narrow window for squeezing in the Dali Museum, I wouldn't recommend doing what I did, which was to buy the ticket about 24 hours ahead of time. (That was in May 2019.)
Thank you all! Tickets are bought.
It really depends on when you're going, which you didn't mention btw. But I see that you sorted it already :)