gpt4 book ai didi

php - 使用 PHP 创建、编辑和删除 crontab 作业?

转载 作者:IT老高 更新时间:2023-10-28 11:48:20 26 4
gpt4 key购买 nike

是否可以使用 PHP 来创建、编辑和删除 crontab 作业?

我知道如何列出 Apache 用户当前的 crontab 作业:

$output = shell_exec('crontab -l');
echo $output;

但是如何用 PHP 添加一个 cron 任务呢? 'crontab -e' 只会打开一个文本编辑器,您必须在保存文件之前手动编辑条目。

以及如何使用 PHP 删除 cron 作业?同样,您必须通过 'crontab -e' 手动执行此操作。

使用这样的作业字符串:

$job = '0 */2 * * * /usr/bin/php5 /home/user1/work.php';

如何使用 PHP 将其添加到 crontab 作业列表中?

最佳答案

crontab 命令用法

usage:  crontab [-u user] file
crontab [-u user] [ -e | -l | -r ]
(default operation is replace, per 1003.2)
-e (edit user's crontab)
-l (list user's crontab)
-r (delete user's crontab)
-i (prompt before deleting user's crontab)

所以,

$output = shell_exec('crontab -l');
file_put_contents('/tmp/crontab.txt', $output.'* * * * * NEW_CRON'.PHP_EOL);
echo exec('crontab /tmp/crontab.txt');

只要用户具有足够的文件写入权限,以上内容即可用于创建和编辑/追加

删除作业:

echo exec('crontab -r');

另外,请注意 apache 以特定用户身份运行,并且通常不是 root,这意味着只能为 apache 用户更改 cron 作业,除非将 crontab -u 权限授予 apache用户。

关于php - 使用 PHP 创建、编辑和删除 crontab 作业?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4421020/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com