views:

108

answers:

3

This is really annoying me as I have done it before, about a year ago and I cannot for the life of me remember what library it was.

Basically, the problem is that I want to be able to call a method a certain number of times or for a certain period of time at a specified interval.

One example would be I would like to call a method "x" starting from now, 10 times, once every 0.5 seconds. Alternatively, call method "x" starting from now, 10 times, until 5 seconds have passed.

Now I thought I used a boost library for this functionality but I can't seem to find it now and feeling a bit annoyed. Unfortunately I can't look at the code again as I'm not in possession of it any more.

Alternatively, I could have dreamt this all up and it could have been proprietary code. Assuming there is nothing out there that does what I would like, what is currently the best way of producing this behaviour? It would need to be high-resolution, up to a millisecond.

It doesn't matter if it blocks the thread that it is executed from or not.

Thanks!

+1  A: 

A combination of boost::this_thread::sleep and time duration found in boost::datetime?

Nikko
Thanks, it does look like I'll be able to knock something up with these two. I was sure there was a library that implemented that functionality though, must have dreamt it.
Aetius
A: 

It's probably bad practice to answer your own question but I wanted to add something more to what Nikko suggested as I have no implemented the functionality with the two suggested libraries. Someone might find this useful at some point.

void SleepingExampleTest::sleepInterval(int frequency, int cycles, boost::function<void()> method) {
    boost::posix_time::time_duration interval(boost::posix_time::microseconds(1000000 / frequency));
    boost::posix_time::ptime timer = boost::posix_time::microsec_clock::local_time() + interval;

    boost::this_thread::sleep(timer - boost::posix_time::microsec_clock::local_time());

    while(cycles--) {
        method();

        timer = timer + interval;
        boost::this_thread::sleep(timer - boost::posix_time::microsec_clock::local_time());
    }
}

Hopefully people can understand this simple example that I have knocked up. Using a bound function just to allow flexibility.

Appears to work with about 50 microsecond accuracy on my machine. Before taking into account the skew of the time it takes to execute the method being called the accuracy was a couple of hundred microseconds, so definitely worth it.

Aetius
+1  A: 

Maybe you are talking about boost::asio. It is a mainly used for networking, but it can be used for scheduling timers.

It can be used in conjunction with boost::threads.

J. Calleja