I would like to set an alarm (similar to signal.alarm) where the granularity is finer than integer seconds. For example, I'd like to set an alarm for 0.4 seconds or 3.2 seconds. I'm particularly interested in alarms that last for less than one second.
In Python 3, I have only tried "import signal" and calling "signal.alarm(time)" where "time" is an integer. If "time" is a floating point number, the call fails. This is not surprising because the documentation says "time" must be an integer.
At one point in Python 2, I found some code that implemented access to "ualarm()" from Python but all of this is quite obsolete at this point.
You can use signal.setitimer
for that:
signal.setitimer(signal.ITIMER_REAL, 0.5)
Of course, there are also all sorts of higher-level ways to arrange to do something 0.5 seconds from now, so going through low-level signal APIs may not be the best approach for what you're doing.
Also, keep in mind that the C sleep
and usleep
functions may be implemented using SIGALRM
, so it's not safe to mix calls to signal.setitimer
or signal.alarm
with anything that might call C sleep
or usleep
. (Python's time.sleep
doesn't use those functions, so it's probably fine.)