使用PHP创建,编辑和删除crontab作业? [英] Use PHP to create, edit and delete crontab jobs?

查看:460
本文介绍了使用PHP创建,编辑和删除crontab作业?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用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用户,这意味着cron作业只能为apache用户更改,除非为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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆