본문 바로가기

python

thread 예시 (시계)

 

1초에 한번씩 시간이 반복적으로 프린트되는 시계

break로 지정한 조건에 부합하면 프로그램이 종료된다.

# thread를 사용한 디지털 시간 출력
import time

now = time.localtime()
print(now)
print('{}년 {}월 {}일 {}시 {}분 {}초'.format(now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec))

print('-------')
import threading

def cal_show():
    now = time.localtime()
    print('{}년 {}월 {}일 {}시 {}분 {}초'.format(  
        now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec))

def my_run():
    while True:
        now2 = time.localtime()
        if now2.tm_min == 10: break  # 10분에 프로그램 종료
        cal_show()
        time.sleep(1)

th = threading.Thread(target=my_run)
th.start()

th.join()
print('프로그램 종료')

time.struct_time(tm_year=2022, tm_mon=10, tm_mday=13, tm_hour=10, tm_min=9, tm_sec=48, tm_wday=3, tm_yday=286, tm_isdst=0)
2022년 10월 13일 10시 9분 48초
-------
2022년 10월 13일 10시 9분 48초
2022년 10월 13일 10시 9분 49초
2022년 10월 13일 10시 9분 50초
2022년 10월 13일 10시 9분 51초
2022년 10월 13일 10시 9분 52초
2022년 10월 13일 10시 9분 53초
2022년 10월 13일 10시 9분 54초
2022년 10월 13일 10시 9분 55초
2022년 10월 13일 10시 9분 56초
2022년 10월 13일 10시 9분 57초
2022년 10월 13일 10시 9분 58초
2022년 10월 13일 10시 9분 59초
프로그램 종료