1

I want to create a 30sec timer in Python with async but I don't know how I can do.

I tried with this code but it blocks all the code:

def restore_presences(self, loop):
    async def func():
        db, c = self.connect()
        c.execute('SELECT Presenza FROM Teachers')
        presences = c.fetchall()
        for item in presences:
            c.execute('UPDATE Teachers SET Presenza = ?', ('no',))
            db.commit()
        db.close()

    threading.Thread(target=lambda loop: loop.run_until_complete(func()), args=(loop,)).start()


# THIS BLOCKS MY CODE
t = Timer(30, self.restore_presences, args=[asyncio.get_event_loop()])
t.start()
t.join()
# THIS BLOCKS MY CODE

The async function runs perfectly.

sophros
  • 14,672
  • 11
  • 46
  • 75
alex3025
  • 109
  • 4
  • 21
  • Do not call join if you dont want to wait for the thread...That just to begin with. Why are you using both async and threading? – Netwave Apr 13 '19 at 11:14
  • Ok, thanks. But can I save the timer so when I close the program and I reopen it, it continue? Ex. 30s timer. I close the program and when I open it after 10s the timer is 20s. – alex3025 Apr 13 '19 at 11:19
  • Well, you can save the timer counter and start it again from the last counter point... – Netwave Apr 13 '19 at 11:20
  • Possible duplicate of [How to timeout an async test in pytest with fixture?](https://stackoverflow.com/questions/55684737/how-to-timeout-an-async-test-in-pytest-with-fixture) – sophros May 28 '19 at 12:13

0 Answers0