You have seen the built in poll function, right? Maybe you need something more flexible. You might have a look at that code.