๐Ÿ”ฅ TIL - Day 28

Kim Dae Hyunยท2021๋…„ 10์›” 14์ผ
0

TIL

๋ชฉ๋ก ๋ณด๊ธฐ
32/93

ํ”„๋กœ์ ํŠธ์—์„œ ๋งค์ผ ์˜ค์ „ 9์‹œ์— ๋ฐœ์˜๋ฒ•์•ˆ API๋กœ๋ถ€ํ„ฐ ๋ฐ›์€ ์–ด์ œ์ž ๋ฐœ์˜๋ฒ•์•ˆ์„ ์‚ฌ์šฉ์ž์—๊ฒŒ ์ด๋ฉ”์ผ๋กœ ์ „์†กํ•˜๋Š” ๊ธฐ๋Šฅ์„ ๊ตฌํ˜„ ์ค‘์— ์žˆ์—ˆ๋‹ค.

ํ˜„์žฌ ํ”„๋กœ์ ํŠธ์—์„œ ์ด 3๊ฐœ์˜ ์Šค์ผ€์ค„๋Ÿฌ๋ฅผ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ๋Š”๋ฐ ๋ฉ”์ผ์ „์†ก ์Šค์ผ€์ค„๋Ÿฌ๋งŒ ์ œ๋Œ€๋กœ ๋™์ž‘์„ ํ•˜์ง€ ์•Š์•˜๋‹ค. ์—๋Ÿฌ ๋กœ๊ทธ๋ฅผ ๋ณด๊ณ  ์—ด์‹ฌํžˆ ๊ตฌ๊ธ€๋ง ํ•œ ๊ฒฐ๊ณผ ์“ฐ๋ ˆ๋“œ ๊ด€๋ จ ๋ฌธ์ œ์ธ ๊ฒƒ ๊ฐ™์€๋ฐ ์•„์ง Flask ์—์„œ ์—๋Ÿฌ ๋กœ๊ทธ๋ฅผ ๋ณด๊ณ  ํ•ด๊ฒฐํ•˜๋Š” ์‹ค๋ ฅ์ด ๋ถ€์กฑํ•ด์„œ ๊ฑฐ์˜ ํฌ๊ธฐ์ƒํƒœ์˜€๋‹ค..

์ผ๋‹จ ์ž”๋จธ๋ฆฌ๋ฅผ ์กฐ๊ธˆ ๊ตด๋ ค๋ณด๊ธฐ๋กœ ํ–ˆ๋‹ค. ์ผ๋‹จ ๊ฒฐ๊ณผ๋ถ€ํ„ฐ ๋งํ•˜์ž๋ฉด ์ž˜ ๋™์ž‘ํ•˜๋„๋ก ์ˆ˜์ •ํ–ˆ๋‹ค.

๐Ÿ“Œ Solution ...!

์ฒ˜์Œ ์˜ค๋ฅ˜๋ฅผ ๋ฐœ์ƒ์‹œํ‚จ ์ ‘๊ทผ๋ฐฉ๋ฒ•์€ APScheduler์˜ Job์œผ๋กœ ๋ฉ”์ผ์„ ์ „์†กํ•˜๋Š” ๋ฉ”์„œ๋“œ๋ฅผ ๊ทธ๋Œ€๋กœ ๋„ฃ์€ ๋ฐฉ์‹์ด๋‹ค. ์‚ฌ์‹ค ๋‹น์—ฐํžˆ ์ด๋ ‡๊ฒŒ ํ•ด์„œ ๋™์ž‘์ด ๋˜์–ด์•ผ ํ•œ๋‹ค. ๊ทผ๋ฐ ์ผ๋‹จ ์—๋Ÿฌ๋ฅผ ๋ฑ‰์–ด๋‚ด๋‹ˆ ๋‹ค๋ฅธ ๋ฐฉ๋ฒ„์„ ์‚ฌ์šฉํ–ˆ๋‹ค.

[ ์ฒซ๋ฒˆ์งธ, ์—๋Ÿฌ๋ฅผ ๋ฐœ์ƒ์‹œํ‚จ ๋ฐฉ๋ฒ• ]

from apscheduler.schedulers.background import BackgroundScheduler, BlockingScheduler
from apscheduler.triggers.cron import CronTrigger

def ๋ฉ”์ผ๋ณด๋‚ด๊ธฐ_๋ฉ”์„œ๋“œ():
	...

cron = "๋ถ„ ์‹œ * * *"

scheduler = BackgroundScheduler(daemon=True)
scheduler.add_job(๋ฉ”์ผ๋ณด๋‚ด๊ธฐ_๋ฉ”์„œ๋“œ, CronTrigger.from_crontab(cron))
scheduler.start()

ํ•ด๊ฒฐํ•œ ๋ฐฉ์‹์ด๋‹ค. ๋ฉ”์ผ์„ ๋ณด๋‚ด๋Š” ๋ฉ”์„œ๋“œ๋ฅผ API๋กœ ๋งคํ•‘์‹œํ‚ค๊ณ  ์Šค์ผ€์ค„๋Ÿฌ์˜ Job์—์„œ๋Š” ํ•ด๋‹น API๋ฅผ ๋ถ€๋ฅด๋Š” ์‹์œผ๋กœ ๋ณ€๊ฒฝํ–ˆ๋‹ค.

[ ๋‘๋ฒˆ์งธ, ์Šค์ผ€์ค„๋Ÿฌ ์ •์ƒ ๋™์ž‘ ]

@app.get('/api/mail')
def ๋ฉ”์ผ๋ณด๋‚ด๊ธฐ_๋ฉ”์„œ๋“œ():
	...


def start_send_mail_job():
    print('์•Œ๋ฆผ ๋ฉ”์ผ ์ „์†ก ์Šค์ผ€์ค„๋Ÿฌ Start')
    requests.get('http://localhost:5000/api/mail')
    print('์•Œ๋ฆผ ๋ฉ”์ผ ์ „์†ก ์Šค์ผ€์ค„๋Ÿฌ End')
    return "ok"

cron = "13 14 * * *"

scheduler = BlockingScheduler(daemon=True)
scheduler.add_job(start_send_mail_job, CronTrigger.from_crontab(cron))
scheduler.start()

EC2์— ์Šค์ผ€์ค„๋Ÿฌ๋“ค์„ ๋ชฐ์•„์„œ ๋ฐฐํฌํ™˜๊ฒฝ์—์„œ ์‚ฌ์šฉ ์ค‘์ธ๋ฐ BackgroundScheduler ์‚ฌ์šฉ์‹œ Job์ด 2๋ฒˆ์”ฉ ์ˆ˜ํ–‰๋˜๋Š” ๋ฌธ์ œ๊ฐ€ ์ƒ๊ฒจ์„œ BlockingScheduler๋กœ ๋ณ€๊ฒฝํ–ˆ๋‹ค.

profile
์ข€ ๋” ์ฒœ์ฒœํžˆ ๊นŒ๋จน๊ธฐ ์œ„ํ•ด ๊ธฐ๋กํ•ฉ๋‹ˆ๋‹ค. ๐Ÿง

0๊ฐœ์˜ ๋Œ“๊ธ€