From 9ea4024c8dc769951bfbe3547417d3043a6f2bac Mon Sep 17 00:00:00 2001 From: Samuel Williams Date: Sun, 28 Jun 2020 21:24:27 +0100 Subject: [PATCH] Shut down the eel server less aggressively At the moment, every time a websocket connection closes, we check 1 second later to see if there any any connections open. If a user opens and terminates multiple websocket connections, this can mean that one of the earlier "1 second laters" comes along during a later shutdown/reconnect and closes the server, despite the user navigating through the app in a reasonable way. This patch moves this check to a "spawn later" gevent greenlet that can be terminated and rescheduled. Every time a websocket is closed, we cancel any previously-running check and schedule a new one for 1 second in the future, which should mean that Eel shuts down less often during valid navigation step/s. Fixes #248 --- eel/__init__.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/eel/__init__.py b/eel/__init__.py index 1ec26310..5b06401e 100644 --- a/eel/__init__.py +++ b/eel/__init__.py @@ -1,6 +1,7 @@ from builtins import range from io import open +from gevent.threading import Timer import gevent as gvt import json as jsn import bottle as btl @@ -25,6 +26,7 @@ _js_functions = [] _mock_queue = [] _mock_queue_done = set() +_shutdown = None # The maximum time (in milliseconds) that Python will try to retrieve a return value for functions executing in JS # Can be overridden through `eel.init` with the kwarg `js_result_timeout` (default: 10000) @@ -326,17 +328,24 @@ def _expose(name, function): _exposed_functions[name] = function +def _detect_shutdown(): + if len(_websockets) == 0: + sys.exit() + + def _websocket_close(page): + global _shutdown + close_callback = _start_args.get('close_callback') if close_callback is not None: sockets = [p for _, p in _websockets] close_callback(page, sockets) else: - # Default behaviour - wait 1s, then quit if all sockets are closed - sleep(1.0) - if len(_websockets) == 0: - sys.exit() + if _shutdown: + _shutdown.kill() + + _shutdown = gvt.spawn_later(1.0, _detect_shutdown) def _set_response_headers(response):