Golang - Why I Created My Own Sleep Function ?

mohammad ali
2 min readSep 23, 2022

Why need to Sleep code execution?

You may ask, why do we even need a sleep function at first place ?

Answer: We may need to run a specific code periodically, we don’t want it to run all the time. For instance, where i am working we are developing a product to send phone numbers to a dialer after every 5 minutes. This process runs in a separate goroutine 24/7 and never returns. It sends large bundles of contacts and then goes to sleep for 5 mins, and after 5 min again wakes up and send next bundles, and so on.

So, initially we used sleep function from time library:

time.Sleep(5 * time.Minute)

But whats wrong with it ? Actually nothing !!

Requirement:

But now we have a new requirement, although it is never stopping process. But we may need to stop it any time ( probably for testing/debugging ). And problem is if we stop this process, it will actually stop after sleep time has passed (5 min in our case) and control is return back to this process.

Solution:

1- Simple Approach:
I created a pointer* bool variable called isCampaignRunning . When user stops the process this becomes false. Now i need to check this variable periodically and return when it becomes false. So i created my own sleeping for loop :

2- More Advance Approach:

This solution is suggested by Teiva Harsanyi ( author of book “100 Go Mistakes” ). Obviously above solution works for us, but it takes at worst 10 seconds before returning. Solution below solves that problem too.

--

--

mohammad ali

I write about the solutions to problems i solve at work being Golang developer. If you want to learn along with me as i learn then hit the follow button.