Search code examples
python-3.xapscheduler

How do I use Python to implement a circular task that executes every 100ms


I needed to simulate two scenarios in which a piece of data would be inserted into the Redis database every 100ms using redis.xadd("stream_name", {"key": "value"}, maxlen=100, approximate=False) which is the function of the Redis-Stream data type. I want to keep the insertion timestamp of the Redis database the same in both scenarios

Therefore, I also need to set the same start time, so that at the same start time and the same loop interval which is 100ms, the insertion time which is used xadd function of two Redis data should be consistent.

I looked up and found that the Apscheduler was a good timing task, but its interval was only up to seconds, not milliseconds.

I don't know what better way to implement my scenario requirements.

I would appreciate it if you could tell me how to solve it?


Solution

  • Not really sure if this will satisfy your requirements but the time.sleep() function can do milliseconds via decimal argument.

    from time import sleep
    
    while True:
        sleep(0.1)  # or 100/1000
        # do something