We help IT Professionals succeed at work.

Multi callback timer under Linux and c/c++

zuse01
zuse01 asked
on
Medium Priority
4,576 Views
Last Modified: 2007-12-19
Hi!
I am looking for an way to handle in c++ and linux timers like in java (timer.schedule) or in Win32/MFC (SetTimer) with a callback after elapsed time. What about support of multiple callbacks with different times???

The SIG_ALRM/alarm does only support 1 callback with bad time resolution of 1 second. But I need multiple callbacks with short intervalls like that:

Timer t1 = new Timer (func1, 1000);
Timer t2 = new Timer (func2, 60);
...

Can anybody give me a tip??? I know how to implement with multiple threads and sleep but is there no implementation out there???

regards
martin

Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2006

Commented:
Hi zuse01,

There is no direct way (API) to do what you want ... If sleep solution is OK with you, the you can use usleep or nanosleep, but be warned that even with nanosleep, best resolution that you can expect is 10ms ... You can use sleep with pthreads to achieve what you want ...

An alternative is presented in linux kernel in the form of timer queue, though programming it might not be convenient ... dont kow if newer kernel versions still support it ...

Sunnycoder

Author

Commented:
hi sunnycoder!

You mean
not convenient to program an interface like in java with phread and sleep
????
CERTIFIED EXPERT
Top Expert 2006

Commented:
zuse01,

I meant not convenient to program in the kernel using timer queues

pthread and usleep will be lot more easy to use

Sunnycoder
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Commented:
hi,

setitimer allow you to specify microsecond resolution.
as far as i can remeber you can only have one timer running at once, but you can easily handle this by doing something similar to that described above. Keep your timers in a queue and when a timer expires (you get SIAG_ALARM) run thru the list calling expire() on each object, then it will see if it has expired and do whatever takes your fancy.

hth
neale
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.