19.5.15

Three ways to poll in golang.

I've been playing with different ways of polling lately on the kuberntes E2E tests.  Here's what ive learned so far.

Using a for loop : Manually code the iteration yourself.

The simplest way to poll in golang is to do it in a for loop like this...




The above methodoloy is obvious - we simply create a for loop with a "sleep" condition.  However there is something annoying here.  What if we want to actually add a timeout ?  Well.. then we have to have a different if/else construct for the timeout...

Using Channels : go to sleep until a timeout trips a channel io.
 
So, a more direct way to accomplish the same polling is to create two channels, one for a timeout, the other for incremental updates.  NOTE This is a different code snippet, but it should be clear how the strategy is different.  The key thing to note is that our for loop has a select block with cases in it.  And those cases just wait on channels that we create above (see deletionStart and tick). 



Using wait.Poll() : use higher level polling construct and just write a boolean function

Finally, quinton-hoole has showed me there is yet a third way to do this sort of polling - use the explicit poll method.  


Now, instead of using the selector and breaking out to T, we use golang's wait.Poll functionality, where we send it a block which returns true (polling is complete) or false (polling isn't complete) and an error field.   If we don't ever return true, polling will eventually time out - and the test will fail.


No comments:

Post a Comment