23
12

More than 3 years have passed since last update.

cronの書き方を学ぶ

Last updated at Posted at 2021-04-14

node.jsで定期実行コマンドを作りたかったので、
cron-nodeを使ってcronを書こうと思ったのですが、

const job = new CronJob('0 */10 * * * *', function() {
   ...
});

0 */10 * * * * ってなんだったっけ...🧐
となったので、cron操作を軽くまとめておきます。

アスタリスクだらけの基礎

* * * * *
こちらがcronの指定の基礎コマンドです。
この指定で、毎分コマンドが実行されます。

左から順に、 分、時、日、月、曜日 となります。
曜日は数字指定で0-7で指定でき、 0,7は日曜日を指します。

毎月、毎日といった指定方法

先ほど言ったように、

分 時 日  月 曜日
*  *  *  *   *

の順に指定すればOKです。
そして、 * は全てが指定されているという考え方です。

30 12 *  *  *

この指定だと毎日12:30に実行されます。

30 12 4

この指定だと毎月4日12:30に実行されます。

数字は複数指定も可能です。

1,5 * * * *

上記だと毎時間1分と5分の二回実行されます。

1-3 * * *

上記だと毎時1分、2分、3分の三回実行されます。

..ごとに実行といった指定方法

/数字 で指定することができます。

* */1 * * *

これは時の部分にスラッシュがあるため、毎時0分一時間おきの実行になります。

組み合わせ

* 10-16/2 * * *

10〜16時の間の2時間ごとに実行されます。

*が六つある場合は!?

https://www.npmjs.com/package/cron
npmにあるcronは*が6つ指定できますが、
これは秒単位で指定できます。

秒 分 時 日  月 曜日
*  *  *  *  *   *

参考

https://blog.mothule.com/tools/how-to-use-cron
https://www.kagoya.jp/howto/rentalserver/cron/

23
12
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
23
12