From 2561febca9281f166b75737bb65618c6ca5e2757 Mon Sep 17 00:00:00 2001 From: zman Date: Mon, 7 Apr 2025 17:26:48 -0400 Subject: [PATCH] f --- app.py | 46 ++++++++++++++++++++++++++++++++-------------- 1 file changed, 32 insertions(+), 14 deletions(-) diff --git a/app.py b/app.py index a9c8e30..fbe6d03 100644 --- a/app.py +++ b/app.py @@ -10,6 +10,7 @@ from PIL import Image import mimetypes import logging from logging.handlers import RotatingFileHandler +import time app = Flask(__name__) @@ -79,20 +80,37 @@ def print_address_label(pdf_path): cut=True ) - app.logger.info("Waiting to acquire printer lock...") - with printer_lock: # Ensure only one thread sends a job at a time - app.logger.info("Sending to printer...") - try: - send( - instructions=instructions, - printer_identifier=printer, - backend_identifier=backend, - blocking=True - ) - app.logger.info("Print job sent successfully") - except Exception as e: - app.logger.error(f"Error during printing: {str(e)}") - + # Try to acquire the printer lock with a timeout + max_retries = 3 + retry_delay = 2 # seconds + for attempt in range(max_retries): + if printer_lock.acquire(timeout=5): # 5 seconds timeout + try: + app.logger.info(f"Attempting to send print job (Attempt {attempt + 1})...") + send( + instructions=instructions, + printer_identifier=printer, + backend_identifier=backend, + blocking=True + ) + app.logger.info("Print job sent successfully") + break + except Exception as e: + app.logger.error(f"Error during printing: {str(e)}") + if attempt < max_retries - 1: + app.logger.info(f"Retrying after {retry_delay} seconds...") + time.sleep(retry_delay) + else: + app.logger.error("Max retries reached. Failed to send print job.") + else: + app.logger.error(f"Failed to acquire printer lock (Attempt {attempt + 1}). Printer is busy.") + if attempt < max_retries - 1: + app.logger.info(f"Retrying after {retry_delay} seconds...") + time.sleep(retry_delay) + else: + app.logger.error("Printer is still busy after retries.") + raise Exception("Printer is busy. Try again later.") + except Exception as e: app.logger.error(f"Error during label printing: {str(e)}")