0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Linux で Crontab と CURL コマンドを組み合わせて CURL を定期実行する方法

Posted at

Crontab と CURL を使った定期実行の基本

Crontab にログインして、以下のコマンドで cron タスクの確認や設定が可能です。

タスクの確認

crontab -l

タスクの設定

crontab -e

Crontab のパラメータ

* * * * * curl http://localhost/api/crontab.php
  • 第1個 * = 分(Minute)
  • 第2個 * = 時(Hour)
  • 第3個 * = 日(Day of month)
  • 第4個 * = 月(Month)
  • 第5個 * = 曜日(Day of week)
  • 第6個 = 実行するコマンド

複雑な設定の場合は、crontab.guru に入力すると次回実行時間を確認できます。


Crontab と CURL の組み合わせ

CURL と組み合わせることで、定期的に自動で実行する必要のある機能や API を呼び出せます。手動で実行する必要はありません。

最も簡単な使い方は、URL を指定してターミナルにレスポンスを表示する方法です。

curl https://www.google.com

HTTP リクエストの利用

CURL では、HTTP リクエスト(GET、POST など)を使うことがあります。

GET メソッドの例

URL にパラメータを付与する場合:

curl https://www.google.com.tw/search?q=curl

POST メソッドの例

curl -X POST --data "email=post@google.com&id=23" www.post/postCurl.php

よく使う CURL オプション

  • -X / --request :HTTP メソッド(GET / POST など)
  • -d / --data :POST パラメータ

Crontab と CURL を組み合わせた実例

毎日 01:10:00 に CURL で API を呼び出す場合:

ローカルホストを呼び出す場合

10 1 * * * curl http://localhost/api/crontab.php

リモートサーバーを呼び出す場合

10 1 * * * curl http://10.10.2.1/api/crontab.php

このように設定すると、API を定期的に自動で呼び出せます。
サーバー上で設定する場合、サーバー上のローカルファイルを呼び出すときは localhost を使ってください。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?