How to execute function for set time

Is there a better way to execute function for 5 seconds than measuring time before execution and comparing it to current time?

Invoke a function repeating every X seconds.
Start a coroutine that will wait for X seconds and then cancel the invoking function