Warlock
Warlock

Reputation: 186

Implementing timer callback in c

I am new to callback functions in C. I want to create a timed callback.

Scenario: I want a timer function which will trigger the callback function when timer expires. For example, every 5 sec the timer expires and calls the function.

How should I approach this problem ?

Upvotes: 0

Views: 4098

Answers (1)

Eregrith
Eregrith

Reputation: 4366

How should you approach this problem?

As with all problems:

  • Figure out what you want to do precisely
  • Ask yourself how you would do it yourself if you needed to (and if you could)
  • Try to formalize previous step as close as possible to single statements sentences, one step at a time.
  • Identify what blocks you / what you don't know how to do. Do some research on that.

What you want to do precisely

You want to "create a timed callback". I think this means :

  • You have a function foo doing some work
  • You have your program running
  • You want to be able to say "From right now, in X miliseconds, call foo" anywhere in your program

How would you do this yourself?

I think you would, for example, launch a stopwatch with X miliseconds then keep doing whatever you were doing. When the stopwatch reaches zero, you stop what you do and do the thing needed. Finally, resume what you were doing.

What blocks you?

Judging by your question I think two things block you:

  • You need to understand how to do function callbacks in C. See "function pointers"
  • You need to understand how to have a timer and do something when the timer reaches zero.

A few google searches will help you with both.

Upvotes: 3

Related Questions