카테고리 없음
[Python] Qtimer의 시작과 종료할 시간 설정하기
오늘밤날다
2024. 5. 3. 13:22
ChatGPT에게 물어본 코드를 조금 수정했다.
import sys
from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import QApplication
from datetime import *
def start_main_timer():
program_init_time = datetime.now()
# 1초 간격으로 타이머 실행
main_timer = QTimer()
main_timer.setInterval(1000)
main_timer.timeout.connect(timer_action)
# 타이머의 시작 시간과 종료시간을 설정 (코드 실행시간으로부터 10초 후 실행, 이후 1분 경과시 종료)
start_time = program_init_time + timedelta(seconds=10) # 9:00 AM
stop_time = start_time + timedelta(minutes=1)
# 매초 check_start_stop함수를 통해서 타이머 실행여부 판단
check_timer = QTimer()
check_timer.setInterval(1000)
check_timer.timeout.connect(lambda: check_start_stop(main_timer, start_time, stop_time))
check_timer.start()
return check_timer
def check_start_stop(main_timer, start_time, stop_time):
current_time = datetime.now()
if start_time <= current_time <= stop_time:
if not main_timer.isActive():
main_timer.start()
print("Main timer started")
else:
if main_timer.isActive():
main_timer.stop()
print("Main timer stopped")
def timer_action():
print(datetime.now(), "Main timer action")
app = QApplication(sys.argv)
check_timer = start_main_timer()
sys.exit(app.exec_())