To make that, you could use interrupts with a timer.