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.9884411.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 timer3. 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 threadLoading script...
Related Posts
- Python - Yaml 파일 파싱하는 방법
- Python - 파일 내용 삭제
- Python - for문에서 리스트 순회 중 요소 값 제거
- Python - 두 리스트에서 공통 요소 값 찾기
- Python - 문자열 앞(뒤)에 0으로 채우기
- Python - 공백으로 문자열 분리
- Python - 중첩 리스트 평탄화(1차원 리스트 변환)
- Python - 16진수 문자열을 Int로 변환
- Python - 두 날짜, 시간 비교
- Python f-string으로 변수 이름, 값 쉽게 출력 (변수명 = )
- Python - nonlocal과 global 사용 방법
- Python 바다코끼리 연산자 := 알아보기
- Python - pip와 requirements.txt로 패키지 관리
- Python - 딕셔너리 보기 좋게 출력 (pprint)
- Python - Requests 사용 방법 (GET/POST/PUT/PATCH/DELETE)
- Python - 온라인 컴파일러 사이트 추천
- Python - os.walk()를 사용하여 디렉토리, 파일 탐색
- Python - 문자열 비교 방법
- Python - Text 파일 읽고 쓰는 방법 (read, write, append)
- Python - 리스트에서 첫번째, 마지막 요소 가져오는 방법
- Python - 두개의 리스트 하나로 합치기
- Python - 리스트의 첫번째 요소 제거
- Python - 리스트의 마지막 요소 제거
- Python 소수점 버림, 4가지 방법
- Python 코드 안에서 버전 확인 방법
- Python 소수점 반올림, round() 예제
- Python - 리스트 평균 구하기, 3가지 방법
- Python - bytes를 String으로 변환하는 방법
- Python - String을 bytes로 변환하는 방법
- Python 버전 확인 방법 (터미널, cmd 명령어)
- Python - 람다(Lambda) 함수 사용 방법
- Python - dict 정렬 (Key, Value로 sorting)
- Python - range() 사용 방법 및 예제
- Python - 리스트를 문자열로 변환
- Python - 문자를 숫자로 변환 (String to Integer, Float)