0%

Line Chatbot - 機器人睡著了?使用Scheduler把他叫醒吧!

由於使用免費的Heroku,所以機器人的server在經過30分鐘的閒置後就會睡著,要喚醒的話會需要一些時間,因此可以建立定期排程的script來讓他執行、保持清醒。

要達到這樣的效果可以用兩種做法

  1. 使用APScheduler
  2. 使用Heroku Scheduler

APScheduler

  1. 安裝套件 pip install apscheduler
  2. 建立一個叫做clock.py的檔案,將這個檔案放在專案的根目錄下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from apscheduler.schedulers.blocking import BlockingScheduler
import urllib.request

sched = BlockingScheduler()

@sched.scheduled_job('cron', day_of_week='mon-fri', minute='*/20')
def scheduled_job():
url = "https://hungrylinebot.herokuapp.com/"
conn = urllib.request.urlopen(url)

print("wake up!")
for key, value in conn.getheaders():
print(key, value)

sched.start()
  1. 在Procfile中加上clock: python clock.py
  2. 把東西都push上去後到專案的resources中把Free Dynos中的clock python clock.py打開

Heroku Scheduler

  1. 在根目錄下建立一個hello.py
1
print("hello world")
  1. 進入Heroku的CLI,打開Account Settings,設定信用卡

  1. 進入專案內的resource,啟用add-ons

  1. 點開Heroku Scheduler - Create Job

參考:第 13 天:LINE BOT SDK:Heroku 夜未眠(一)