@@ -36,14 +36,18 @@ def log(nc, level, content):
3636 "https://huggingface.co/bartowski/Meta-Llama-3.1-8B-Instruct-GGUF/resolve/4f0c246f125fc7594238ebe7beb1435a8335f519/Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf" : { "save_path" : os .path .join (persistent_storage (), "Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf" ) },
3737}
3838app_enabled = Event ()
39-
39+ trigger = Event ()
40+ CHECK_INTERVAL = 5
41+ CHECK_INTERVAL_WITH_TRIGGER = 5 * 60
42+ CHECK_INTERVAL_ON_ERROR = 10
4043
4144@asynccontextmanager
4245async def lifespan (_app : FastAPI ):
4346 set_handlers (
4447 APP ,
4548 enabled_handler , # type: ignore
4649 models_to_fetch = models_to_fetch ,
50+ trigger_handler = trigger_handler
4751 )
4852 nc = NextcloudApp ()
4953 if nc .enabled_state :
@@ -88,11 +92,11 @@ def background_thread_task():
8892 try :
8993 response = nc .providers .task_processing .next_task (list (provider_ids ), list (task_type_ids ))
9094 if not response :
91- sleep ( 5 )
95+ wait_for_tasks ( )
9296 continue
9397 except (NextcloudException , RequestException , JSONDecodeError ) as e :
9498 log (nc , LogLvl .ERROR , f"Network error fetching the next task { e } " )
95- sleep ( 5 )
99+ wait_for_tasks ( CHECK_INTERVAL_ON_ERROR )
96100 continue
97101
98102 task = response ["task" ]
@@ -122,7 +126,6 @@ def background_thread_task():
122126 # Error when reporting the result
123127 exception_info = traceback .format_exception (type (e ), e , e .__traceback__ )
124128 log (nc , LogLvl .ERROR , f"Error: { '' .join (exception_info )} " )
125- sleep (5 )
126129 except Exception as e : # noqa
127130 exception_info = traceback .format_exception (type (e ), e , e .__traceback__ )
128131 log (nc , LogLvl .ERROR , f"Error: { '' .join (exception_info )} " )
@@ -132,8 +135,6 @@ def background_thread_task():
132135 except (NextcloudException , RequestException ) as net_err :
133136 log (nc , LogLvl .INFO , f"Network error in reporting the error: { net_err } " )
134137
135- sleep (5 )
136-
137138
138139def start_bg_task ():
139140 t = Thread (target = background_thread_task , args = ())
@@ -184,5 +185,18 @@ async def enabled_handler(enabled: bool, nc: AsyncNextcloudApp) -> str:
184185 return ""
185186
186187
188+ def trigger_handler (providerId : str ):
189+ print ('TRIGGER called' )
190+ trigger .set ()
191+
192+ def wait_for_tasks (interval = None ):
193+ global CHECK_INTERVAL
194+ global CHECK_INTERVAL_WITH_TRIGGER
195+ actual_interval = CHECK_INTERVAL if interval is None else interval
196+ if trigger .wait (timeout = actual_interval ):
197+ CHECK_INTERVAL = CHECK_INTERVAL_WITH_TRIGGER
198+ trigger .clear ()
199+
200+
187201if __name__ == "__main__" :
188202 run_app ("main:APP" , log_level = "trace" )
0 commit comments