OK, so your train will leave Madrid Chamartin which is the northern station. Accessible by metro or Cercanias train from the airport. There is a pre-boarding security so arrive at the station 30 minutes before departure.
Allowing for the arrival time being ‘wheels down’ not even ‘aircraft come to a stop’ ; immigration, baggage collection etc. I’d still say, yes, you could go that without much stress.
You can book a flexible ticket BUT there is no guarantee that there will be capacity on the later train if your primary booking is for the earlier train.
If you want to cover all the angles book a flexible ticket on both trains. You can cancel >1 hour before departure. If not, just do what I would - book the later train and have a decent lunch.