egersdorfer/crontab

PHP Cron任务管理器

dev-develop 2014-12-22 16:01 UTC

This package is not auto-updated.

Last update: 2024-09-24 04:40:28 UTC


README

简单、独立且本地的PHP Crontab包

此包可以帮助您使用PHP管理本地cron任务。您可以列出、追加和删除任务,并设置日志文件。

需求

应在各种Linux系统中正常工作。

使用示例

使用 composer 安装它,或者简单地将其包含在某个地方:require("crontab/src/Crontab/Crontab.php");

追加两个新任务,并设置为每分钟运行一次

    $cron = new \Crontab\Crontab();
    $cron->setMinute("*");
    $cron->setHour("*");
    $cron->setDayOfMonth("*");
    $cron->setMonth("*");
    $cron->setDayOfWeek("*");
    $cron->append(array(
                "date",
                "ls -all"
            )
        );
    $commandsList = $cron->execute();

方法

append($command)

将新任务追加到当前cron任务列表中

参数: $command : 字符串或命令数组。

  $cron = new \Crontab\Crontab();
  $cron->setMinute("*");
  $cron->setHour("*");
  $cron->setDayOfMonth("*");
  $cron->setMonth("*");
  $cron->setDayOfWeek("*");
  $cron->append("date");
  $cron->execute();

remove($command)

从当前cron任务列表中删除任务。您必须重新创建要删除的确切任务。

参数: $command : 字符串或命令数组

  $cron = new \Crontab\Crontab();
  $cron->setMinute("*");
  $cron->setHour("*");
  $cron->setDayOfMonth("*");
  $cron->setMonth("*");
  $cron->setDayOfWeek("*");
  $cron->remove("date");
  $cron->execute();

getJobs()

返回带有散列键的当前任务列表

  $cron = new \Crontab\Crontab();
  $cron->setMinute("*");
  $cron->setHour("*");
  $cron->setDayOfMonth("*");
  $cron->setMonth("*");
  $cron->setDayOfWeek("*");
  $cron->remove("date");
  $cron->execute();

removeByKey($key)

通过散列键从当前cron任务列表中删除任务。通过执行execute()或getJobs()找到

参数: $key : 字符串或键数组

  $cron = new \Crontab\Crontab();
  $cron->removeByKey("1231231231231231231");
  $cron->execute();

execute()

应用并写入新的cron任务列表。

    $cron->setMinute("*");
    $cron->setHour("*");
    $cron->setDayOfMonth("*");
    $cron->setMonth("*");
    $cron->setDayOfWeek("*");
    $cron->append("date");
    $cron->execute();

clear()

简单地通过执行crontab -r 删除所有正在运行的任务

    $cron = new \Crontab\Crontab();
    $cron->clear();

设置

设置也可以应用于构造方法,如下所示

    $conf = array(
		'minute' => '*',
		'hour' => '*',
		'dayOfMonth' => '*',
		'month' => '*',
		'dayOfWeek' => '*',
		'logFile' => 'log.txt',
		'tmpFile' => 'jobs.txt'
	);

    $cron = new \Crontab\Crontab($conf);

设置函数(默认值均为"*”)

setMinute($m) : Sets the minute.
setHour($h) : Sets the hour.
setDayOfMonth($dom) : Sets the date of the month.
setMonth($m) : Sets the month.
setDayOfWeek($dow) : Sets the day of the week.

日志和临时文件设置

setLogFile($v) : Sets the log file and will attempt to create it. The default is /dev/null ie: nothing logged
setTmpFile($v) : Sets the tempory file used by crontab to read from, this file is automatically removed. The default is "jobs.txt"

助手

从现在开始5分钟后执行此任务。

    $cron = new \Crontab\Crontab();
    $cron->minuteFromNow(5);
    $cron->execute();

帮助理解cron任务

Google搜索应该会提供很多链接,但如果需要帮助,请查看:Kevin van Zonneveld的博客

待办事项

  • 使用电子邮件而不是日志或两者都使用。
  • 内置更多助手函数。
  • 单元测试

免责声明

自行承担使用此库的风险。