1초마다 어떤 작업을 반복적으로 수행하거나, 특정 작업을 수행하도록 만드는 방법을 소개합니다.
1. sleep()을 이용한 방법
반복문과 sleep()
을 이용하여 아래와 같이 1초마다 특정 작업을 반복시킬 수 있습니다.
sleep(second)
는 인자로 전달된 second만큼 지연range(0, 5)
는 0을 포함하고 5를 포함하지 않는 범위 리턴
import time
from datetime import datetime
for i in range(0, 5):
print(f"time: {datetime.now()}")
time.sleep(1)
Output:
time: 2022-12-21 05:41:15.983965
time: 2022-12-21 05:41:16.985076
time: 2022-12-21 05:41:17.986219
time: 2022-12-21 05:41:18.987348
time: 2022-12-21 05:41:19.988441
1.1 무한 반복
무한히 반복할 때는 while True:
를 이용하고, 특정 조건에서 반복문을 탈출하도록 조건을 구현하시면 됩니다.
import time
from datetime import datetime
while True:
print(f"time: {datetime.now()}")
time.sleep(1)
2. Timer를 이용한 방법
Timer는 어떤 함수를 특정 시간 뒤에 한번 실행되도록 만들 수 있습니다.
1초 간격으로 특정 함수가 실행되도록 하려면, 1초 간격으로 Timer를 실행시켜야 합니다.
아래 예제는 Timer를 이용하여 1초 뒤에 함수를 실행하고, 작업이 완료되었을 때 1초 뒤에 함수를 실행하도록 타이머를 설정합니다.
InfiniteTimer
클래스에 주기적으로 Timer를 실행하는 내용을 구현_handle_target()
함수에서 인자로 전달된 함수를 실행하고_start_timer()
를 호출하여 타어머를 재설정
import time
from datetime import datetime
from threading import Timer
class InfiniteTimer:
def __init__(self, seconds, target):
self.is_running = False
self.seconds = seconds
self.target = target
self.thread = None
def _handle_target(self):
self.target()
self._start_timer()
def _start_timer(self):
self.thread = Timer(self.seconds, self._handle_target)
self.thread.start()
def start(self):
if not self.is_running:
self.is_running = True
self._start_timer()
else:
print("Timer already started or running.")
def cancel(self):
if self.thread is not None:
if self.is_running:
self.thread.cancel()
self.is_running = False
else:
print("Timer never started or failed to initialize.")
def task():
print(f"time: {datetime.now()}")
# Setup and start the timer
timer = InfiniteTimer(1, task)
timer.start()
print(f"Wait for the timer: {datetime.now()}")
time.sleep(10)
print("Cancel the timer")
timer.cancel()
Output:
Wait for the timer: 2022-12-21 06:03:51.744050
time: 2022-12-21 06:03:52.744209
time: 2022-12-21 06:03:53.744831
time: 2022-12-21 06:03:54.745281
time: 2022-12-21 06:03:55.752788
time: 2022-12-21 06:03:56.753054
time: 2022-12-21 06:03:57.753381
time: 2022-12-21 06:03:58.753896
time: 2022-12-21 06:03:59.754346
time: 2022-12-21 06:04:00.754634
Cancel the timer
3. Thread를 이용한 방법
Thread를 이용하여 주기적으로 특정 작업을 수행할 수 있습니다.
아래 예제는 MyThread 클래스를 생성하였고, 인자로 전달된 함수와 시간 간격으로 특정 작업이 주기적으로 실행되도록 구현하였습니다.
import time
from datetime import datetime
from threading import Thread
class MyThread(Thread):
def __init__(self, interval, target):
Thread.__init__(self)
self._stopped = False
self._interval = interval
self._target = target
def stop(self):
self._stopped = True
def run(self):
while not self._stopped:
self._target()
time.sleep(1)
def task():
print(f"time: {datetime.now()}")
# Setup and start the thread
t = MyThread(1, task)
t.start()
print(f"Wait for the thread: {datetime.now()}")
time.sleep(10)
print("Stop the thread")
t.stop()
Output:
time: 2022-12-21 06:24:32.205889
Wait for the thread: 2022-12-21 06:24:32.205949
time: 2022-12-21 06:24:33.207095
time: 2022-12-21 06:24:34.208250
time: 2022-12-21 06:24:35.209065
time: 2022-12-21 06:24:36.210256
time: 2022-12-21 06:24:37.210564
time: 2022-12-21 06:24:38.211194
time: 2022-12-21 06:24:39.212331
time: 2022-12-21 06:24:40.213417
time: 2022-12-21 06:24:41.214535
time: 2022-12-21 06:24:42.214698
Stop the thread
Loading script...
Related Posts
- Python 에러 해결, 'conda' 용어가 cmdlet, 함수, 스크립트 ... 인식되지 않습니다.
- Python 에러 해결, AttributeError: module 'jwt' has no attribute 'encode'
- Python - assert 사용 방법
- Python - Counter로 Collection 개수 세기
- Python - enumerate(), for/index 예제
- Python - count(), len() 함수
- Python - join() 함수, 문자열 합치기
- Python - 줄바꿈 입력 방법
- Python - 딕셔너리를 JSON으로 변환
- Python - JSON을 딕셔너리로 변환
- Python - 딕셔너리 Index로 접근/순회 방법
- Python - 딕셔너 리 CSV 파일 쓰기/읽기
- Python - 딕셔너리 update() 함수
- Python - JSON 예쁘게(pretty), 정렬하여 출력
- Python - CSV 파일을 JSON 파일로 변환
- Python - CSV 파일을 리스트로 변환
- Python - List를 Set로 변환
- Python - Set을 List로 변환
- Python - 텍스트 파일 이어서 쓰기
- Python - 파일 끝 찾기
- Python - 파일 수정 시간, 생성 시간 확인