To have accurate timing you will need to interrupt base the routine. You can use the RTC for that.