timer file descriptor HOWTO

发行 :

1.13

This HOWTO discusses Python’s support for the linux timer file descriptor.

范例

The following example shows how to use a timer file descriptor to execute a function twice a second:

# Practical scripts should use really use a non-blocking timer,
# we use a blocking timer here for simplicity.
import os, time
# Create the timer file descriptor
fd = os.timerfd_create(time.CLOCK_REALTIME)
# Start the timer in 1 second, with an interval of half a second
os.timerfd_settime(fd, initial=1, interval=0.5)
try:
    # Process timer events four times.
    for _ in range(4):
        # read() will block until the timer expires
        _ = os.read(fd, 8)
        print("Timer expired")
finally:
    # Remember to close the timer file descriptor!
    os.close(fd)