herokuでアドオン使わずにcron (Python)
herokuにはcronがない。で、どうやってcron的な定期実行を実現するかというと王道はHeroku Schedulerというアドオンを使うらしい。ただ、アドオンを使うとなると基本的に無料とはいえクレジットカードを登録する必要があってそれが嫌だったのでアドオン使わない方法で実現した。
ソースbot.py
from apscheduler.schedulers.blocking import BlockingScheduler sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=3) def timed_job(): print('This job runs every three minutes.') sched.start()
APScheduler
が必要なのでインストールして
$ pip install apscheduler
requirements.txt
に以下の行を追加する。
APScheduler==3.0.3
Procfile
を書いて
bot: python bot.py
bot.py
,requirements.txt
,Procfile
をcommitしてデプロイ。
$ git push heroku master
あとは
$ heroku ps:scale bot=1
でプロセス1個割り当てれば3分おきにジョブが走るのを確認できる。
2015-05-24T10:24:15.052174+00:00 heroku[bot.1]: Starting process with command `python bot.py` 2015-05-24T10:24:15.662122+00:00 heroku[bot.1]: State changed from starting to up 2015-05-24T10:27:16.551515+00:00 app[bot.1]: This job runs every three minutes. 2015-05-24T10:30:16.551654+00:00 app[bot.1]: This job runs every three minutes. 2015-05-24T10:33:16.554967+00:00 app[bot.1]: This job runs every three minutes.
平日毎日夕方5時、みたいな指定も可能。ただし実行時刻はUTC(協定世界時)になるので注意。
@sched.scheduled_job('cron', day_of_week='mon-fri', hour=17) def scheduled_job(): print('This job runs every weekday at 5pm.')