파이썬 타이머에 문제가있는 동안 저는 bottle.py가 "reloader = True"로 실행될 때 모든 타이머 함수가 빠르게 연속적으로 두 번 실행된다는 것을 발견했습니다.
타이머를 호출하는 몇 가지 다른 방법으로 이것을 시도했으며 결과는 모든 인스턴스에서 동일합니다 (이중 실행).
샘플 코드 :
#!/usr/bin/env python
from threading import Timer
from bottle import *
# Short timer
def short_time():
t = Timer(1, short_time)
t.daemon = True
t.start()
print "Short Time..."
# Long timer
def long_time():
t = Timer(5, long_time)
t.daemon = True
t.start()
print "Long Time..."
# The App
app = Bottle()
@app.route('/status')
def default():
return "OK"
#Run the app -----
if __name__ == '__main__':
# Start the short timer.
short_time()
# Start the long timer.
long_time()
# Run the app
# This interferes with the timers
run(app, host='0.0.0.0', port=8002, reloader=True)
#This one works as expected
#run(app, host='0.0.0.0', port=8002) #This works fine
리 로더가 활성화 된 출력 :
Short Time...
Short Time...
Short Time...
Short Time...
Short Time...
Short Time...
Short Time...
Short Time...
Long Time...
Short Time...
Long Time...
Short Time...
Short Time...
Short Time...
예상 출력 (리 로더 없음) :
Short Time...
Short Time...
Short Time...
Short Time...
Long Time...
Short Time...
Short Time...
Short Time...
Short Time...
Short Time...
Long Time...
Short Time...
Short Time...
reloader를 사용하는 방법에 대한 아이디어가 있지만 타이머 문제를 방지합니까?
때 reloader=True
설정, 병 공정 자식 프로세스로 스크립트를 재 - 실행 :
if reloader and not os.environ.get('BOTTLE_CHILD'): import subprocess lockfile = None try: fd, lockfile = tempfile.mkstemp(prefix='bottle.', suffix='.lock') os.close(fd) # We only need this file to exist. We never write to it while os.path.exists(lockfile): args = [sys.executable] + sys.argv environ = os.environ.copy() environ['BOTTLE_CHILD'] = 'true' environ['BOTTLE_LOCKFILE'] = lockfile p = subprocess.Popen(args, env=environ)
그런 다음 1 초 마다 자식이 다시 시작 됩니다 interval
(기본값 1).
스크립트의 최상위 레벨에서 실행되는 모든 것은 bottle 서버를 시작할 때와 자식 프로세스가 다시 시작될 때마다 실행됩니다.
따라서 부모 프로세스 와 자식 프로세스 모두 독립적으로 타이머를 실행합니다. 5 초까지되기 전에 해당 프로세스로 실행 결코 극복 자식 프로세스의 긴 타이머가 사망하지만, 짧은 타이머가 있습니다 단지 부모 프로세스가 다시 시작하는 아이를 죽이기 전에 화재로 관리 할 수 있습니다.
BOTTLE_CHILD
환경 변수를 테스트하여 하위 프로세스에 있는지 감지 할 수 있습니다 .
import os
if os.environ.get('BOTTLE_CHILD'):
# in the child process, do something special perhaps?
# this will be executed *each time the child is restarted*
else:
# in the parent process, which restarts the child process
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다