https://apscheduler.readthedocs.io/en/latest/
Advanced Python Scheduler
파이썬의 스케줄러 모듈입니다. cron 또는 툭정 주기로 해당 기능을 실행하고자
할 경우 유용하게 사용가능합니다.
클서버의 우분투 18.04 가상서버에서 python3 로 테스트 되었습니다.
해당 모듈을 pip 로 설치합니다.
# pip install apscheduler
Collecting apscheduler
Downloading https://files.pythonhosted.org/packages/97/3a/fa3213cc325091b7729616594611fff31d72c2d4d590418c3efdf7424ae2/APScheduler-3.5.3-py2.py3-none-any.whl (57kB)
100% |████████████████████████████████| 61kB 657kB/s
Requirement already satisfied: setuptools>=0.7 in /root/venv/lib/python3.5/site-packages (from apscheduler)
Collecting pytz (from apscheduler)
Downloading https://files.pythonhosted.org/packages/61/28/1d3920e4d1d50b19bc5d24398a7cd85cc7b9a75a490570d5a30c57622d34/pytz-2018.9-py2.py3-none-any.whl (510kB)
100% |████████████████████████████████| 512kB 1.2MB/s
Collecting tzlocal>=1.2 (from apscheduler)
Downloading https://files.pythonhosted.org/packages/cb/89/e3687d3ed99bc882793f82634e9824e62499fdfdc4b1ae39e211c5b05017/tzlocal-1.5.1.tar.gz
Collecting six>=1.4.0 (from apscheduler)
Downloading https://files.pythonhosted.org/packages/73/fb/00a976f728d0d1fecfe898238ce23f502a721c0ac0ecfedb80e0d88c64e9/six-1.12.0-py2.py3-none-any.whl
Installing collected packages: pytz, tzlocal, six, apscheduler
Running setup.py install for tzlocal ... done
Successfully installed apscheduler-3.5.3 pytz-2018.9 six-1.12.0 tzlocal-1.5.1
아래는 샘플로 제공되는 예제 소스입니다. 3초마다 현재 시간을 출력하는 프로그램입니다.
#!/usr/bin/env python
#-*- coding: utf-8 -*-
from datetime import datetime
import time
import os
from apscheduler.schedulers.background import BackgroundScheduler
def tick():
print('Tick! The time is: %s' % datetime.now())
if __name__ == '__main__':
scheduler = BackgroundScheduler()
scheduler.add_job(tick, 'interval', seconds=3)
scheduler.start()
print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))
try:
# This is here to simulate application activity (which keeps the main thread alive).
while True:
time.sleep(2)
except (KeyboardInterrupt, SystemExit):
# Not strictly necessary if daemonic mode is enabled but should be done if possible
scheduler.shutdown()
scheduler.py 로 저장 후 실행합니다.
# chmod 700 scheduler.py
# ./scheduler.py
Tick! The time is: 2019-03-06 15:31:29.575756
Tick! The time is: 2019-03-06 15:31:32.574832
Tick! The time is: 2019-03-06 15:31:35.575011
Tick! The time is: 2019-03-06 15:31:38.575306