จากที่คุณแจ้งว่าโปรแกรมหยุดรอให้การเล่นเสียงจบ ทำให้เมื่อมีการกลับออนไลน์ของโฮสต์หลายรายการพร้อมกันเกิดการรอคิวขึ้นมา ปัญหานี้น่าจะเกิดจากการที่การเล่นเสียงเป็นการดำเนินการแบบ blocking ซึ่งทำให้ thread ที่เรียกใช้งานต้องรอกระบวนการเล่นเสียงให้เสร็จสิ้นก่อนที่จะดำเนินการต่อไป
เพื่อแก้ไขปัญหานี้ เราสามารถทำให้การเล่นเสียงเป็นแบบไม่ blocking โดยใช้ threading อีกชั้นหนึ่ง หรือใช้ asynchronous programming (ถ้า framework ของคุณรองรับ) นี่คือวิธีที่คุณสามารถปรับปรุงฟังก์ชัน schedule_host_deletion:
1. เปลี่ยนการเล่นเสียงให้เป็นแบบไม่ blocking ด้วย threading
คุณสามารถสร้าง thread ใหม่สำหรับการเล่นเสียง แยกออกจากฟังก์ชันหลักที่จัดการการลบโฮสต์ ดังนี้:
import threading
def schedule_host_deletion(hostname, offline_dict, update_signal, settings_widget, lock, main_window):
def delete_host():
normalized_hostname = hostname.upper()
with lock:
if normalized_hostname in offline_dict:
store_name = offline_dict[normalized_hostname]['store_name']
# Log the host coming online
log_online(
hostname,
store_name,
offline_dict,
normalized_hostname,
offline_dict[normalized_hostname]['inspect_status']
)
# Remove the host from the offline_dict
del offline_dict[normalized_hostname]
# Save the offline state
save_offline_state('offline_state.json', offline_dict)
# Play sound when host comes back online
hostname_lower = hostname.lower()
if any(fnmatch.fnmatch(hostname_lower, pattern.lower()) for pattern in settings_widget.sound_alert_patterns):
if hasattr(main_window, 'sound_manager'):
message = f"Big C {store_name} return to Online"
audio_filename = f"{message}.mp3"
audio_path = os.path.join('sounds', audio_filename)
fallback_sound_file = "returnonline.mp3"
def play_sound():
if os.path.exists(audio_path):
main_window.sound_manager.play(audio_path)
else:
print(f"Sound file '{audio_filename}' does not exist. Attempting to download...")
downloaded_file = download_audio(message)
if downloaded_file and os.path.exists(downloaded_file):
main_window.sound_manager.play(downloaded_file)
else:
if os.path.exists(fallback_sound_file):
print(f"Failed to download. Playing fallback sound file: {fallback_sound_file}")
main_window.sound_manager.play(fallback_sound_file)
else:
print("Failed to download sound file and no fallback sound available.")
# เรียกใช้การเล่นเสียงใน thread ใหม่
sound_thread = threading.Thread(target=play_sound)
sound_thread.start()
# Remove from exception hosts if necessary
if normalized_hostname in settings_widget.exception_hosts:
settings_widget.exception_hosts.remove(normalized_hostname)
settings_widget.update_exception_hosts_signal.emit(settings_widget.exception_hosts)
else:
print(f"Hostname {normalized_hostname} was not in offline_dict")
# Emit the update signal to refresh the GUI
update_signal.emit()
# Schedule the deletion after 5 seconds
timer = threading.Timer(5.0, delete_host)
timer.start()
2. ใช้ Thread Pool
การสร้าง thread ใหม่ทุกครั้งเมื่อมีการเรียกใช้ฟังก์ชันอาจทำให้เกิดการใช้ทรัพยากรมากเกินไปเมื่อมีการเรียกใช้งานหลายครั้งพร้อมกัน วิธีที่ดีกว่าเป็นการใช้ thread pool ซึ่งจะจัดการ thread ให้มีประสิทธิภาพมากขึ้น ตัวอย่างเช่น ใช้ concurrent.futures.ThreadPoolExecutor:
import threading
from concurrent.futures import ThreadPoolExecutor
# สร้าง ThreadPoolExecutor ที่ระดับ global หรือในที่ที่เหมาะสม
executor = ThreadPoolExecutor(max_workers=10)
def schedule_host_deletion(hostname, offline_dict, update_signal, settings_widget, lock, main_window):
def delete_host():
normalized_hostname = hostname.upper()
with lock:
if normalized_hostname in offline_dict:
store_name = offline_dict[normalized_hostname]['store_name']
# Log the host coming online
log_online(
hostname,
store_name,
offline_dict,
normalized_hostname,
offline_dict[normalized_hostname]['inspect_status']
)
# Remove the host from the offline_dict
del offline_dict[normalized_hostname]
# Save the offline state
save_offline_state('offline_state.json', offline_dict)
# Play sound when host comes back online
hostname_lower = hostname.lower()
if any(fnmatch.fnmatch(hostname_lower, pattern.lower()) for pattern in settings_widget.sound_alert_patterns):
if hasattr(main_window, 'sound_manager'):
message = f"Big C {store_name} return to Online"
audio_filename = f"{message}.mp3"
audio_path = os.path.join('sounds', audio_filename)
fallback_sound_file = "returnonline.mp3"
def play_sound():
if os.path.exists(audio_path):
main_window.sound_manager.play(audio_path)
else:
print(f"Sound file '{audio_filename}' does not exist. Attempting to download...")
downloaded_file = download_audio(message)
if downloaded_file and os.path.exists(downloaded_file):
main_window.sound_manager.play(downloaded_file)
else:
if os.path.exists(fallback_sound_file):
print(f"Failed to download. Playing fallback sound file: {fallback_sound_file}")
main_window.sound_manager.play(fallback_sound_file)
else:
print("Failed to download sound file and no fallback sound available.")
# ส่งงานไปยัง ThreadPoolExecutor
executor.submit(play_sound)
# Remove from exception hosts if necessary
if normalized_hostname in settings_widget.exception_hosts:
settings_widget.exception_hosts.remove(normalized_hostname)
settings_widget.update_exception_hosts_signal.emit(settings_widget.exception_hosts)
else:
print(f"Hostname {normalized_hostname} was not in offline_dict")
# Emit the update signal to refresh the GUI
update_signal.emit()
# Schedule the deletion after 5 seconds
timer = threading.Timer(5.0, delete_host)
timer.start()
การใช้ ThreadPoolExecutor จะช่วยจัดการ thread ได้อย่างมีประสิทธิภาพมากขึ้น และป้องกันการสร้าง thread มากเกินไปในกรณีที่มีการเรียกใช้ฟังก์ชันจำนวนมากพร้อมกัน
3. ตรวจสอบว่า sound_manager.play เป็นการดำเนินการแบบไม่ blocking
ขึ้นอยู่กับการ implement ของ sound_manager.play ถ้ามันเป็นการดำเนินการแบบ blocking คุณอาจจะต้องปรับเปลี่ยนมันให้เป็นแบบไม่ blocking หรือใช้ library ที่รองรับการเล่นเสียงแบบ non-blocking เช่น pygame, playsound ในโหมดแยก thread เป็นต้น
ตัวอย่างการใช้ playsound แบบไม่ blocking:
from playsound import playsound
import threading
def play_sound_non_blocking(audio_path):
threading.Thread(target=playsound, args=(audio_path,), daemon=True).start()
แล้วในฟังก์ชัน play_sound ของคุณให้เรียกใช้ play_sound_non_blocking(audio_path) แทน
4. ใช้ Asynchronous Programming (ถ้าใช้ Framework ที่รองรับ)
ถ้าคุณใช้ Framework ที่รองรับ asynchronous เช่น asyncio ในการจัดการ GUI (เช่น asyncio กับ aiohttp), คุณสามารถเปลี่ยนฟังก์ชันให้เป็นแบบ async ได้ แต่ต้องแน่ใจว่า Framework ของคุณรองรับการใช้งานแบบนี้
สรุป
การเล่นเสียงในแบบไม่ blocking จะช่วยให้โปรแกรมของคุณยังคงตอบสนองได้ดีเมื่อมีการกลับออนไลน์ของโฮสต์หลายรายการพร้อมกัน การใช้ threading หรือ ThreadPoolExecutor เป็นวิธีที่ดีในการแยกการดำเนินการเล่นเสียงออกจากฟังก์ชันหลักที่จัดการการลบโฮสต์ นอกจากนี้ยังควรตรวจสอบว่า Library การเล่นเสียงที่ใช้รองรับการเล่นแบบไม่ blocking ด้วย
หากคุณมีคำถามเพิ่มเติมหรือต้องการความช่วยเหลือเพิ่มเติมเกี่ยวกับการ implement โปรดแจ้งรายละเอียดเพิ่มเติมมาได้เลยนะครับ!