2014-09-03 5 views
0

나는 다음과 같은 몇 가지 반복 작업을 실행하는 데 APScheduler을 사용하고 있습니다 :이 스크립트는 단순히 종료 while True 루프를 추가 종료 할 때 interval_job이 종료Python 스크립트를 계속 실행하는 가장 좋은 방법은 무엇입니까?

from apscheduler.scheduler import Scheduler 
from time import time, sleep 

apsched = Scheduler() 
apsched.start() 

def doSomethingRecurring(): 
    pass # Do something really interesting here.. 

apsched.add_interval_job(doSomethingRecurring, seconds=2) 

while True: 
    sleep(10) 

때문입니다. 나는 이것이 최고인지는 알지 못한다. 이 작업을 수행하는 "더 나은"방법이 있습니까? 모든 팁을 환영합니다!

+0

http://stackoverflow.com/questions/8685695/how-do-i-run-long-term-infinite-python-processes는 – Piddien

답변

1

차단 스케줄러를 사용해보십시오. apsched.start()는 막을 것입니다. 시작하기 전에 설정해야합니다.

편집 : 의견에 대한 일부 의사 코드.

apsched = BlockingScheduler() 

def doSomethingRecurring(): 
    pass # Do something really interesting here.. 

apsched.add_job(doSomethingRecurring, trigger='interval', seconds=2) 

apsched.start() # will block 
+0

나는 종류의 답변에 의해 의아해하고 있습니다. 보시다시피 저는 실제로'apsched.start()'를 사용하고 있습니다. 내가 시작하기 전에 준비해야한다고 제안 했어. 무슨 뜻인지 설명해 주시겠습니까? 몇 가지 예제 코드가 환영받을 것입니다! – kramer65

1

이 코드를 사용해보십시오. 이 데몬으로 파이썬 스크립트를 실행합니다 :

import os 
import time 

from datetime import datetime 
from daemon import runner 


class App(): 
    def __init__(self): 
     self.stdin_path = '/dev/null' 
     self.stdout_path = '/dev/tty' 
     self.stderr_path = '/dev/tty' 
     self.pidfile_path = '/var/run/mydaemon.pid' 
     self.pidfile_timeout = 5 

    def run(self): 
     filepath = '/tmp/mydaemon/currenttime.txt' 
     dirpath = os.path.dirname(filepath) 
     while True: 
      if not os.path.exists(dirpath) or not os.path.isdir(dirpath): 
       os.makedirs(dirpath) 
      f = open(filepath, 'w') 
      f.write(datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')) 
      f.close() 
      time.sleep(10) 


app = App() 
daemon_runner = runner.DaemonRunner(app) 
daemon_runner.do_action() 

사용법 :

> python mydaemon.py 
usage: md.py start|stop|restart 
> python mydaemon.py start 
started with pid 8699 
> python mydaemon.py stop 
Terminating on signal 15 
관련 문제