Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to do a timer in UNIX

Tags:

c

linux

unix

timer

I always notice people have different reactions to different ways of creating a timer in UNIX.

I know a few different ways that I could make an event execute every X seconds within UNIX:

  • you can do a polling thread - pthread_t with sleeps;
  • you can do a select() with a timeout;
  • and I guess you can use the OS in a few other ways.

Can someone provide some sample code with the "best" or most efficient way to do a timer and a description of why it is the best? I'd like to use the most efficient mechanism for this but I'm not sure which one it is!

For our purposes, just pretend you're printing "Hello World!" once every 10 seconds.

NOTE: I don't have TR1/Boost/etc. on this system, so please keep it to straight-up C/C++ and UNIX system calls. Sorry for not mentioning that the first time :)

like image 685
John Humphreys Avatar asked Aug 25 '11 14:08

John Humphreys


People also ask

How do I run a timer in Linux?

Using the timer command in Linux We must remember that the sleep command allows us to set a time before executing a task. In this case, it will count down from 15 seconds to the end. The time units are seconds (default), minutes (m), hours (h) and days (d). And that's how easy it is to use it.

Is there a timer in Linux?

h header file and main point of this structure is to store dynamic timers in the Linux kernel. Actually, the Linux kernel provides two types of timers called dynamic timers and interval timers. First type of timers is used by the kernel, and the second can be used by user mode.

How do I sleep in a bash script?

How to Use the Bash Sleep Command. Sleep is a very versatile command with a very simple syntax. It is as easy as typing sleep N . This will pause your script for N seconds, with N being either a positive integer or a floating point number.


1 Answers

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.

like image 162
doron Avatar answered Sep 22 '22 03:09

doron