n 초마다 특정 코드 실행
이 질문에는 이미 답변이 있습니다.
예를 들어, Hello World!
n 초마다 인쇄하는 방법이 있습니까? 예를 들어, 프로그램은 내가 가진 모든 코드를 통과 한 다음 5 초 (와 time.sleep()
)가되면 해당 코드를 실행합니다. Hello World를 인쇄하지 않고 파일을 업데이트하는 데 이것을 사용합니다.
예를 들면 다음과 같습니다.
startrepeat("print('Hello World')", .01) # Repeats print('Hello World') ever .01 seconds
for i in range(5):
print(i)
>> Hello World!
>> 0
>> 1
>> 2
>> Hello World!
>> 3
>> Hello World!
>> 4
import threading
def printit():
threading.Timer(5.0, printit).start()
print "Hello, World!"
printit()
# continue with the rest of your code
https://docs.python.org/3/library/threading.html#timer-objects
start () 및 stop () 컨트롤을 사용하여 Alex Martelli의 답변을 일반화 한 주제에 대해 겸손하게 생각합니다.
from threading import Timer
class RepeatedTimer(object):
def __init__(self, interval, function, *args, **kwargs):
self._timer = None
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.is_running = False
self.start()
def _run(self):
self.is_running = False
self.start()
self.function(*self.args, **self.kwargs)
def start(self):
if not self.is_running:
self._timer = Timer(self.interval, self._run)
self._timer.start()
self.is_running = True
def stop(self):
self._timer.cancel()
self.is_running = False
용법:
from time import sleep
def hello(name):
print "Hello %s!" % name
print "starting..."
rt = RepeatedTimer(1, hello, "World") # it auto-starts, no need of rt.start()
try:
sleep(5) # your long-running job goes here...
finally:
rt.stop() # better in a try/finally block to make sure the program ends!
풍모:
- 표준 라이브러리 만, 외부 종속성 없음
start()
그리고stop()
타이머가 이미 시작된 경우에도 여러 번 전화를 안전 / 정지- function to be called can have positional and named arguments
- You can change
interval
anytime, it will be effective after next run. Same forargs
,kwargs
and evenfunction
!
Save yourself a schizophrenic episode and use the Advanced Python scheduler: http://pythonhosted.org/APScheduler
The code is so simple:
from apscheduler.scheduler import Scheduler
sched = Scheduler()
sched.start()
def some_job():
print "Every 10 seconds"
sched.add_interval_job(some_job, seconds = 10)
....
sched.shutdown()
def update():
import time
while True:
print 'Hello World!'
time.sleep(5)
That'll run as a function. The while True:
makes it run forever. You can always take it out of the function if you need.
Here is a simple example compatible with APScheduler 3.00+:
# note that there are many other schedulers available
from apscheduler.schedulers.background import BackgroundScheduler
sched = BackgroundScheduler()
def some_job():
print('Every 10 seconds')
# seconds can be replaced with minutes, hours, or days
sched.add_job(some_job, 'interval', seconds=10)
sched.start()
...
sched.shutdown()
Alternatively, you can use the following. Unlike many of the alternatives, this timer will execute the desired code every n seconds exactly (irrespective of the time it takes for the code to execute). So this is a great option if you cannot afford any drift.
import time
from threading import Event, Thread
class RepeatedTimer:
"""Repeat `function` every `interval` seconds."""
def __init__(self, interval, function, *args, **kwargs):
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.start = time.time()
self.event = Event()
self.thread = Thread(target=self._target)
self.thread.start()
def _target(self):
while not self.event.wait(self._time):
self.function(*self.args, **self.kwargs)
@property
def _time(self):
return self.interval - ((time.time() - self.start) % self.interval)
def stop(self):
self.event.set()
self.thread.join()
# start timer
timer = RepeatedTimer(10, print, 'Hello world')
# stop timer
timer.stop()
Here's a version that doesn't create a new thread every n
seconds:
from threading import Event, Thread
def call_repeatedly(interval, func, *args):
stopped = Event()
def loop():
while not stopped.wait(interval): # the first call is in `interval` secs
func(*args)
Thread(target=loop).start()
return stopped.set
The event is used to stop the repetitions:
cancel_future_calls = call_repeatedly(5, print, "Hello, World")
# do something else here...
cancel_future_calls() # stop future calls
See Improve current implementation of a setInterval python
You can start a separate thread whose sole duty is to count for 5 seconds, update the file, repeat. You wouldn't want this separate thread to interfere with your main thread.
참고URL : https://stackoverflow.com/questions/3393612/run-certain-code-every-n-seconds
'development' 카테고리의 다른 글
C ++에서 메모리 누수를 피하기위한 일반 지침 (0) | 2020.07.07 |
---|---|
JavaScript에 마지막 방법이없는 이유는 무엇입니까? (0) | 2020.07.07 |
Xcode 8-누락 된 파일 경고 (0) | 2020.07.07 |
위도 / 경도 좌표를 일치시키기위한 정규식? (0) | 2020.07.07 |
Xcode / 시뮬레이터 : 이전 iOS 버전을 실행하는 방법은 무엇입니까? (0) | 2020.07.07 |