You will want to look at interrupts.