trinity
trinity

Reputation: 10484

How to run something every t seconds in C?

In C, I want a block of statements to be executed repeatedly every t seconds. How do I do this?

Upvotes: 6

Views: 1498

Answers (4)

Suresh Krishnan
Suresh Krishnan

Reputation: 202

Agree with unwind's recommendation for alarm() but don't forget to set another alarm() after you are done with the periodic processing block.

Upvotes: 0

Matteo Italia
Matteo Italia

Reputation: 126827

If your application runs on Windows, instead, you can use the SetTimer function.

Upvotes: 1

unwind
unwind

Reputation: 399863

This cannot be done in standard C, you need to use some platform-specific API.

One popular choice is POSIX' alarm() function.

This is a "pure" aynchronuous solution. It's of course possible to measure and handle time in other ways, but they're still platform-dependent. You could use sleep() (again, POSIX) to just block. If you combine that with your desired statements in a loop, that should work too.

Upvotes: 7

Mick
Mick

Reputation: 5197

You will need to create a thread or process that runs a loop containing a wait request.

Upvotes: 3

Related Questions