1. schedule λͺ¨λ“ˆ

pip install schedule
import schedule
import time
 
def job():
    #TO DO
    ...
#-------------------------------
# 10μ΄ˆμ— ν•œλ²ˆμ”© μ‹€ν–‰
schedule.every(10).second.do(job)

# 10뢄에 ν•œλ²ˆμ”© μ‹€ν–‰
schedule.every(10).minutes.do(job)

# 맀 μ‹œκ°„ μ‹€ν–‰
schedule.every().hour.do(job)

# 맀일 10:30 에 μ‹€ν–‰
schedule.every().day.at("10:30").do(job)

# 맀주 μ›”μš”μΌ μ‹€ν–‰
schedule.every().monday.do(job)

# 맀주 μˆ˜μš”μΌ 13:15 에 μ‹€ν–‰
schedule.every().wednesday.at("13:15").do(job)
 

while True: # μŠ€μΌ€μ₯΄μ„ μ§€μ†μ μœΌλ‘œ μœ μ§€ν•˜κΈ° μœ„ν•¨
    schedule.run_pending() # μŠ€μΌ€μ₯΄μ„ 체크
    time.sleep(1) # 1μ΄ˆμ— ν•œ λ²ˆμ”© 

ν”„λ‘œκ·Έλž¨ μ§œμ„œ μžλ™ μ‹€ν–‰ ν”„λ‘œκ·Έλž¨μœΌλ‘œ λ“±λ‘ν•΄λ†“μœΌλ©΄ λ˜κ² λ‹€β€¦

β†’ μ•„λ‹ˆλ©΄ 24μ‹œκ°„ λŒλ €μ§€λŠ” μ„œλ²„μ—λ‹€κ°€β€¦

2. apscheduler λͺ¨λ“ˆ

방식 (β†’ νŒŒλΌλ―Έν„°κ°€ 달라짐)

  1. cron : cron ν‘œν˜„μ‹μœΌλ‘œ μˆ˜ν–‰
  2. date: νŠΉμ • λ‚ μ§œμ— μˆ˜ν–‰
  3. interval: 일정 주기둜 μˆ˜ν–‰

μŠ€μΌ€μ₯΄ μ’…λ₯˜

단일 μˆ˜ν–‰: BlockingScheduler

λ‹€μˆ˜ μˆ˜ν–‰: BackgroundScheduler

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.base import JobLookupError

import time

def job():
    print("I'm working...", "| [time] "
          , str(time.localtime().tm_hour) + ":"
          + str(time.localtime().tm_min) + ":"
          + str(time.localtime().tm_sec))

def job_2():
    print("Job2 μ‹€ν–‰: ", "| [time] "
          , str(time.localtime().tm_hour) + ":"
          + str(time.localtime().tm_min) + ":"
          + str(time.localtime().tm_sec))

# stat으둜 객체 생성 -> start ν•΄μ£Όκ³ 
sched = BackgroundScheduler()
sched.start()

# add_job 을 μ΄μš©ν•΄ μˆ˜ν–‰ν•  것을 등둝

# interval - 맀 3μ΄ˆλ§ˆλ‹€ μ‹€ν–‰
sched.add_job(job, 'interval', seconds=3, id="test_2")

# cron μ‚¬μš© - 맀 5μ΄ˆλ§ˆλ‹€ job μ‹€ν–‰
sched.add_job(job, 'cron', second='*/5', id="test_1")

## : id λŠ” 고유 μˆ˜ν–‰λ²ˆν˜Έλ‘œ 겹치면 μˆ˜ν–‰λ˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.
## λ§Œμ•½ 겹치면 λ‹€μŒμ˜ μ—λŸ¬ λ°œμƒ 
## => 'Job identifier (test_1) conflicts with an existing job'

# cron 으둜 ν•˜λŠ” κ²½μš°λŠ” λ‹€μŒκ³Ό 같이 νŒŒλΌλ―Έν„°λ₯Ό 상황에 따라 μ—¬λŸ¬κ°œ 넣어도 λ©λ‹ˆλ‹€.
sched.add_job(job_2, 'cron', minute="59", second='10', id="test_10")
#	λ§€μ‹œκ°„ 59λΆ„ 10μ΄ˆμ— μ‹€ν–‰ν•œλ‹€λŠ” 의미.

count = 0
while True:
    print("Running main process...............")
    time.sleep(1)

job에 νŒŒλΌλ―Έν„°λ₯Ό λ°›μ•„ μ‹€ν–‰ν•˜λŠ” 경우

# νŒŒλΌλ―Έν„°λ₯Ό λ°›μ•„μ„œ μ‹€ν–‰ν•˜λŠ” Job μΌ€μ΄μŠ€
def job(test_str, test_str2):
    print("Hello: %s, %s " % (test_str, test_str2))

# νŒŒλΌλ―Έν„°λ₯Ό λ„£μ–΄μ„œ μ‹€ν–‰ν•˜λŠ” 경우.
# λ§Œμ•½ νŒŒλΌλ―Έν„°λ₯Ό λ°›λŠ”λ°λ„ 넣지 μ•ŠμœΌλ©΄ λ‹€μŒκ³Ό 같은 μ—λŸ¬κ°€ μƒκΉλ‹ˆλ‹€.
# ValueError: The list of positional arguments is longer than the target callable can handle (allowed: 0, given in args: 2)
# args 에 값은 λ°˜λ“œμ‹œ λ°°μ—΄λ‘œ λ„£μ–΄μ•Ό ν•©λ‹ˆλ‹€.
sched.add_job(job, 'cron', minute="1", second='*/5', id="test_11", args=["ν…ŒμŠ€νŠΈ", "λ°˜κ°€μ›Œμš”"])

μ‹œκ°„μ— 따라 이미 λ“±λ‘λ˜μ–΄ μžˆλŠ” Job μ œκ±°ν•˜κ³  싢은 경우