How to efficiently do many tasks a “little later” in Python?

后端 未结 10 896
心在旅途
心在旅途 2021-01-30 11:59

I have a process, that needs to perform a bunch of actions \"later\" (after 10-60 seconds usually). The problem is that those \"later\" actions can be a lot (1000s), so using a

10条回答
  •  生来不讨喜
    2021-01-30 12:24

    Another option is to use the Phyton GLib bindings, in particular its timeout functions.

    It's a good choice as long as you don't want to make use of multiple cores and as long as the dependency on GLib is no problem. It handles all events in the same thread which prevents synchronization issues. Additionally, its event framework can also be used to watch and handle IO-based (i.e. sockets) events.

    UPDATE:

    Here's a live session using GLib:

    >>> import time
    >>> import glib
    >>> 
    >>> def workon(thing):
    ...     print("%s: working on %s" % (time.time(), thing))
    ...     return True # use True for repetitive and False for one-time tasks
    ... 
    >>> ml = glib.MainLoop()
    >>> 
    >>> glib.timeout_add(1000, workon, "this")
    2
    >>> glib.timeout_add(2000, workon, "that")
    3
    >>> 
    >>> ml.run()
    1311343177.61: working on this
    1311343178.61: working on that
    1311343178.61: working on this
    1311343179.61: working on this
    1311343180.61: working on this
    1311343180.61: working on that
    1311343181.61: working on this
    1311343182.61: working on this
    1311343182.61: working on that
    1311343183.61: working on this
    

提交回复
热议问题