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:
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 :)
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.
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 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With