LoginSignup
4
6

More than 5 years have passed since last update.

Heroku上で気軽にcron実行したい

Last updated at Posted at 2018-10-20

はじめに

herokuにデプロイしたアプリをいい感じに定期実行したいな
↪︎HerokuSchedulerで対応できるのか🤔
↪︎クレカの登録面倒だしcronチックに設定できないかな

Node.js上で定期的にLINE通知を送ってくるアプリに組み込みました。

結論

const nodeCron = require('node-cron');

var task = nodeCron.schedule('0 */12 * * *', function() {
  // 定期実行する処理
});
task.start(); // タスクの実行 task.stop()を呼び出すまで定期実行してくれる

Cronの時刻フォーマット

┌──────────── 分(0〜59)
| ┌────────── 時(0〜23)
| | ┌──────── 日(1〜31)
| | | ┌────── 月(1〜12)
| | | | ┌──── 曜日(0〜7  0も7も日曜日 Calendarクラスは滅びるべき)
| | | | |
* * * * *

参考リンク:node-cron

Herokuがアイドル状態になるのを防ぐ

30分アクセスが無いとアプリがアイドル状態になってしまい、task.start()でエラーが起きるため、
アイドル状態にならないように叩き起こす必要がある。
そこでUptime Robotを使う

参考記事:Herokuでアイドルさせないようにした際のメモ

4
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
6