使用 PHP 创建、编辑和删除 crontab 作业? [英] Use PHP to create, edit and delete crontab jobs?
问题描述
是否可以使用 PHP 来创建、编辑和删除 crontab 作业?
Is it possible to use PHP to create, edit and delete crontab jobs?
我知道如何列出 Apache 用户的当前 crontab 作业:
I know how to list the current crontab jobs of the Apache user:
$output = shell_exec('crontab -l');
echo $output;
但是如何使用 PHP 添加 cron 作业呢?'crontab -e' 只会打开一个文本编辑器,您必须在保存文件之前手动编辑条目.
But how to add a cron job with PHP? 'crontab -e' would just open a text editor and you will have to manually edit the entries before saving the file.
以及如何使用 PHP 删除 cron 作业?同样,您必须通过crontab -e"手动执行此操作.
And how to delete a cron job with PHP? Again you have to manually do this by 'crontab -e'.
使用这样的作业字符串:
With a job string like this:
$job = '0 */2 * * * /usr/bin/php5 /home/user1/work.php';
如何使用 PHP 将其添加到 crontab 作业列表中?
How do I add it to the crontab jobs list with PHP?
推荐答案
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');
只要用户具有足够的文件写入权限,上述内容可用于创建和编辑/追加.
The above can be used for both create and edit/append provided the user has the adequate file write permission.
要删除作业:
echo exec('crontab -r');
另外,请注意 apache 以特定用户身份运行,通常不是 root,这意味着只能为 apache 用户更改 cron 作业,除非授予 apache 的 crontab -u
权限用户.
Also, take note that apache is running as a particular user and that's usually not root, which means the cron jobs can only be changed for the apache user unless given crontab -u
privilege to the apache user.
这篇关于使用 PHP 创建、编辑和删除 crontab 作业?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!