@@ -400,6 +400,14 @@ def stop_job_thread(self, timeout_seconds: Optional[float] = _UNSET):
400400 self ._download_pool .shutdown ()
401401 self ._download_pool = None
402402
403+ if self ._download_pool is not None :
404+ # Wait for downloads to complete before shutting down
405+ _log .info ("Waiting for download tasks to complete before stopping..." )
406+ while self ._download_pool .num_pending_tasks () > 0 :
407+ time .sleep (0.5 )
408+ self ._download_pool .shutdown ()
409+ self ._download_pool = None
410+
403411 if self ._thread is not None :
404412 self ._stop_thread = True
405413 if timeout_seconds is _UNSET :
@@ -513,6 +521,8 @@ def run_jobs(
513521 ).values ()
514522 )
515523 > 0
524+
525+ or self ._worker_pool .num_pending_tasks () > 0
516526 ):
517527 self ._job_update_loop (job_db = job_db , start_job = start_job , stats = stats )
518528 stats ["run_jobs loop" ] += 1
@@ -523,7 +533,20 @@ def run_jobs(
523533 stats ["sleep" ] += 1
524534
525535 # TODO; run post process after shutdown once more to ensure completion?
526- self .stop_job_thread ()
536+ # Wait for all download tasks to complete
537+ if self ._download_results and self ._download_pool is not None :
538+ _log .info ("Waiting for download tasks to complete..." )
539+ while self ._download_pool .num_pending_tasks () > 0 :
540+ self ._process_threadworker_updates (
541+ worker_pool = self ._download_pool ,
542+ job_db = job_db ,
543+ stats = stats
544+ )
545+ time .sleep (1 ) # Brief pause to avoid busy waiting
546+ _log .info ("All download tasks completed." )
547+
548+ self ._worker_pool .shutdown ()
549+ self ._download_pool .shutdown ()
527550
528551 return stats
529552
0 commit comments