If the user has been inactive for a certain time, a function must be performed.General approach: Plan the performance of the function for a specified time and, at any user activity, move the launch to a later date.To just plan the function. func 5 seconds in Piton without blocking the main flow:import threading
timer = threading.Timer(5, func)
timer.start()
If timer.cancel() No call, five seconds later. func() In the background flow.To adapt to your task, a method is needed. restart() add which will start the countdown at any user activity. This approach is sufficiently widespread to earn its name: https://en.wikipedia.org/wiki/Watchdog_timer :watchdog = WatchdogTimer(timeout, func, daemon=True)
watchdog.start()
... здесь программа что-то делает
и перезапускает отсчёт при любой активности пользователя
watchdog.restart()
в конце отменяем вызов func совсем или просто из программы выходим
watchdog.cancel()
where https://stackoverflow.com/a/34115590/4279 ♪Here. https://stackoverflow.com/a/31076523/4279 Total https://en.wikipedia.org/wiki/X_Window_System ♪Flows need not be used, for example, in a programme that uses https://docs.python.org/3/library/asyncio.html :async def watchdog(loop, last_activity_time, timeout, func, *args):
"Run *func(args) if more than timeout seconds since last_activity_time."
while (loop.time() - last_activity_time()) < timeout:
await asyncio.sleep(1)
return func(*args)
The purpose of this realization is simple: so far the difference between the current time (see annex).loop.time()) and time-written latest user activity (last_activity_time()less than the specified value (timeoutSleep. Otherwise caused by the assigned function (func) You can come up with a solution that doesn't use asyncio.sleep(1)♪Example of use:#!/usr/bin/env python3
import asyncio
import random
loop = asyncio.get_event_loop()
user = {'last_activity': loop.time()}
asyncio.ensure_future(watchdog(loop, lambda: user['last_activity'], 5,
print, 'idle'))
async def simulate_activity():
for i in range(20):
print(i)
if random.random() < .1:
user['last_activity'] = loop.time() # user have done something now
await asyncio.sleep(1)
loop.run_until_complete(simulate_activity())
Programme printing idleif the user is simulated with help random Total simulate_activity() coroutine, it doesn't show up for too long.