Adding Context Manger to threading.Timer

Proposing to add context management to threading.Timer.

I had an issue where I didn’t want to ask the user to be patient unless they had already been waiting a while. Timer works nicely for this:

    t = Timer(1, print, ("Trust me, I'm on it...",))
    t.start()
    time.sleep(2)
    t.cancel()

Enclosing calls of start and cancel call out for context management for the obvious reasons. Sub-classing and adding it was trivial:

    class Timer(Timer):
        def __enter__(self):
            self.start()

        def __exit__(self, exc_type, exc_val, exc_tb):
            self.cancel()

The first example now looks like this:

    with Timer(1, print, ("Trust me, I'm on it...",)):
        time.sleep(2)

Users of the threading module will probably already be familiar with the context management features of a lock. Chaining the two together is a great way to provide feedback IF it’s needed, gotta reduce that alarm fatigue!

    hold_message = Timer(
        10, 
        print, 
        ("Please hold, your call is important to us...",)
    )

    with some_lock, hold_message:
        ...

Am I in the right place to progress this?

1 Like

Yes. But I do not have the knowledge/experience needed to comment.

I’ve never used the Timer class, so I don’t have much of an opinion myself, but the proposal seems simple and useful enough that I’d suggest simply submitting a PR to add the feature.

3 Likes

Related :
https://discuss.python.org/t/add-a-stopwatch-class-to-the-timeit-module/