15
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPでcron記法をparse

Last updated at Posted at 2014-07-17

朝出掛けにcronの設定したらうっかり毎分実行のタスクとかを作ってしまったので自戒のためメモ。

まちがわないために

mtdowlingがcron parserを作ってくれているのでそれを使ってチェックすればいける。

サンプル

composer.json

{
    "require": {
        "mtdowling/cron-expression": "1.0.*",
        "phpunit/phpunit": "*"
    }
}
<?php
require_once 'vendor/autoload.php';
date_default_timezone_set("Asia/Tokyo");

class CronTest extends PHPUnit_Framework_TestCase {
        // ヒャッハー
	public static $cron = "* * * * * /usr/bin/php /path/to/batch.php\n";

	public function testCronExpression()
	{
		$content = $this->getCronContent();
		$base = strtotime(date("Y-m-d H:i:00")) + 60;

		foreach (explode("\n", $content) as $line) {
			$cron = Cron\CronExpression::factory(substr($line, 0, $this->seekOffset($line)));
			// 今の時間から3回分の実行予定時刻を得る
                        //実際はもっとナイスに書かないといけないけどこれでテストきる
			$dates = $cron->getMultipleRunDates(3);
			foreach ($dates as $date) {
				$next = $date->format("Y-m-d H:i:s");
				$this->assertEquals(date("Y-m-d H:i:s", $base), $next);
				$base += 60;
			}
		}
	}

	public function seekOffset($line)
	{
		$line = trim($line);
		$length = strlen($line);
		$count = 0;
		if ($line[0] == '@') {
			// てきとーに
			return strpos($line, " ");
		} else {
			for ($i = 0; $i < $length; $i++) {
				if ($line[$i] == " ") {
					$count++;
				}
				if ($count == 5) {
					return $i+1;
				}
			}
		}

		throw new InvalidArgumentException("passed valued doesn't contain cron expression");
	}

	public function getCronContent()
	{
		return trim(self::$cron);
	}
}

というか

出掛けにcron設定するとかどうよ、ワタシ(ヽ'ω`)

15
16
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
15
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?