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?

CodeIgniter3でCronジョブを実装する2つの方法

Posted at

はじめに

CodeIgniterでCronジョブを実装する方法について、2つのアプローチを検証しました。それぞれの実装方法のメリット・デメリットを解説します。

1. CodeIgniterコントローラーを使用する方法

コントローラーの実装

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Cron_tester extends CI_Controller {
    public function __construct() {
        parent::__construct();
    }

    public function index() {
        $timestamp = date('Y-m-d H:i:s');
        log_message('error', '"Cron_tester" --> This file is for cron test at ' . $timestamp);
        echo "CRON test completed at " . $timestamp . "\n";
    }
}

Cron設定

*/1 * * * * php /path/to/project/html/index.php Cron_tester

メリット

  • CodeIgniterのフレームワーク機能が使える
  • データベースアクセスが容易
  • ライブラリやヘルパーが使用可能
  • log_message()などのフレームワーク機能が使える

デメリット

  • フレームワークの読み込みが必要で、若干重い
  • 実行時間が比較的長くなる可能性がある

2. 独立したPHPスクリプトを使用する方法

スクリプトの実装

<?php
$timestamp = date('Y-m-d H:i:s');
$log_file = '/path/to/project/logs/log-' . date('Y-m-d') . '.php';

// PHPログファイルのヘッダーがなければ追加
if (!file_exists($log_file)) {
    file_put_contents($log_file, "<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>\n\n");
}

// CodeIgniter形式のログメッセージを追加
$log_message = "ERROR - " . $timestamp . " --> CronTester --> This file is for cron test at " . $timestamp . "\n";
file_put_contents($log_file, $log_message, FILE_APPEND);

echo "CRON test completed at " . $timestamp . "\n";

Cron設定

*/1 * * * * php /path/to/project/app/ci/application/periodic/CronTester.php

メリット

  • シンプルで軽量
  • 実行が高速
  • フレームワークに依存しない
  • 直接ファイル操作が可能

デメリット

  • フレームワークの機能が使えない
  • データベース接続などは自前で実装が必要

Cronの設定について

基本的な書式

* * * * * コマンド
│ │ │ │ │
│ │ │ │ └── 曜日 (0-7)
│ │ │ └──── 月 (1-12)
│ │ └────── 日 (1-31)
│ └──────── 時 (0-23)
└────────── 分 (0-59)

設定方法

1. crontabの編集

crontab -e

2. 設定の確認

crontab -l

注意点

  • cronの設定後は再起動不要
  • ログファイルのパーミッション設定が重要
  • 絶対パスの使用を推奨
  • テスト時は短い間隔で実行して動作確認することを推奨
  • root と user で crontab は別々に存在する
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?