Best way to do a timer in UNIX Best way to do a timer in UNIX unix unix

Best way to do a timer in UNIX


It depends on what you are wanting to do. A simple sleep will suffice for your trivial example of waiting 10 sec between "Hello"s since you might as well suspend your current thread until your time is up.

Things get more complicated if your thread is actually doing something while you are waiting. If you are responding to incoming connections, you will already be using select in such a case a timeout to your select statement makes the most sense for your housekeeping.

If you are processing stuff in a tight loop, you might regularly poll a start time to see if your 10 seconds are up.

alarm with an appropriate signal handler will work as well but there are severe limits to what you can do in a signal handler. Most of the time, it involved setting a flag that will need to be polled every so often.

In a nutshell, it comes down to how your thread is processing events.


Use an event-driven loop like Boost.Asio

#include <iostream>#include <boost/asio.hpp>#include <boost/bind.hpp>#include <boost/date_time/posix_time/posix_time.hpp>class Timer{public:    Timer(            boost::asio::io_service& io_service         ) :        _impl( io_service )    {        this->wait();    }private:    void wait()    {        _impl.expires_from_now( boost::posix_time::seconds(10) );        _impl.async_wait(                boost::bind(                    &Timer::handler,                    this,                    _1                    )                );    }    void handler(            const boost::system::error_code& error            )    {        if ( error ) {            std::cerr << "could not wait: " << boost::system::system_error(error).what() << std::endl;            return;        }        std::cout << "Hello World!" << std::endl;        this->wait();    }private:    boost::asio::deadline_timer _impl;};int main(){    boost::asio::io_service io;    Timer t( io );    io.run();    return 0;}

build & run:

stackoverflow samm$ ./a.outHello World!Hello World!Hello World!^Cstackoverflow samm$ 


If your program is already threaded, then using a poll thread is simple and effective.

If your program is not already threaded, then it gets trickier. Can you use a separate process to do the job? If so, then using multi-processing instead of multi-threading.

If you cannot use an autonomous thread of control (process or thread), then it depends on how your program is organized, which is why there are many preferred alternatives (they are preferred for different circumstances). It also depends on the accuracy of timing that you require. With multi-second gaps and no hard real-time response requirement, you might use an alarm and the SIGALRM handler can set a flag and your main processing loop can monitor the flag at convenient, sensible points and do the activity. This is somewhat messy (because signals are messy), but without a more detailed description of your requirements and constraints, it is hard to know what else to suggest.

So, in summary, there isn't a single universally best solution because different programs are written in different styles and under different constraints.