Possible Duplicate:
Linux C/C++ Timer signal handler in userspace
How do i got about creating a timer in C? I want to perform certain action once every 5 seconds and another one every 2 seconds?
How do i go about achieving this? Could anyone point out some good links or code ?
The problem is not in setting a periodic timer, but to have two timers with a different period.
Unfortunately 2 does not divide 5, but we can have a 1s resolution timer and a counter, when the counter is a multiple of 2, or a multiple of 5, you do what you want. You register the signal handler as usual with a timer, but this handler should look like this:
In order to get rid of overflow issues, we can reset the counter to 0 when we reach a multiple of 2 and 5, for example by doing:
Note that this technique generalizes well to more than 2 periods, but if you are out of luck, the smallest common denominator may be a very small period, so that you may get a high timer signal rate for very little use. For instance if you have a 999ms period, and a 1000ms period, you end up having a signal every ms, which is not really ideal in terms of accuracy and in terms of overhead, but for 2s and 5s this should really be acceptable to have a signal every second.