使用 PHP 创建、编辑和删除 crontab 作业?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4421020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use PHP to create, edit and delete crontab jobs?
提问by datasn.io
Is it possible to use PHP to create, edit and delete crontab jobs?
是否可以使用 PHP 来创建、编辑和删除 crontab 作业?
I know how to list the current crontab jobs of the Apache user:
我知道如何列出 Apache 用户的当前 crontab 作业:
$output = shell_exec('crontab -l');
echo $output;
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'.
以及如何使用 PHP 删除 cron 作业?同样,您必须通过“crontab -e”手动执行此操作。
With a job string like this:
使用这样的作业字符串:
$job = '0 */2 * * * /usr/bin/php5 /home/user1/work.php';
How do I add it to the crontab jobs list with PHP?
如何使用 PHP 将其添加到 crontab 作业列表中?
回答by ajreal
crontab command usage
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)
So,
所以,
$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/appendprovided the user has the adequate file write permission.
如果用户具有足够的文件写入权限,则上述内容可用于创建和编辑/追加。
To delete jobs:
要删除作业:
echo exec('crontab -r');
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.
另外,请注意 apache 以特定用户身份运行,并且通常不是 root 用户,这意味着除非授予 apache 用户crontab -u
特权,否则只能为 apache 用户更改 cron 作业。
回答by Chris Suszyński
We recently prepared a mini project (PHP>=5.3) to manage the cron files for private and individual tasks. This tool connects and manages the cron files so you can use them, for example per project. Unit Tests available :-)
我们最近准备了一个小项目(PHP>=5.3)来管理私人和个人任务的 cron 文件。此工具连接和管理 cron 文件,以便您可以使用它们,例如每个项目。单元测试可用:-)
Sample from command line:
来自命令行的示例:
bin/cronman --enable /var/www/myproject/.cronfile --user www-data
Sample from API:
来自 API 的示例:
use php\manager\crontab\CrontabManager;
$crontab = new CrontabManager();
$crontab->enableOrUpdate('/tmp/my/crontab.txt');
$crontab->save();
Managing individual tasks from API:
从 API 管理单个任务:
use php\manager\crontab\CrontabManager;
$crontab = new CrontabManager();
$job = $crontab->newJob();
$job->on('* * * * *');
$job->onMinute('20-30')->doJob("echo foo");
$crontab->add($job);
$job->onMinute('35-40')->doJob("echo bar");
$crontab->add($job);
$crontab->save();
github: php-crontab-manager
github:php-crontab-manager
回答by RafaSashi
Check a cronjob
检查定时任务
function cronjob_exists($command){
$cronjob_exists=false;
exec('crontab -l', $crontab);
if(isset($crontab)&&is_array($crontab)){
$crontab = array_flip($crontab);
if(isset($crontab[$command])){
$cronjob_exists=true;
}
}
return $cronjob_exists;
}
Append a cronjob
附加一个 cronjob
function append_cronjob($command){
if(is_string($command)&&!empty($command)&&cronjob_exists($command)===FALSE){
//add job to crontab
exec('echo -e "`crontab -l`\n'.$command.'" | crontab -', $output);
}
return $output;
}
Remove a crontab
删除 crontab
exec('crontab -r', $crontab);
Example
例子
exec('crontab -r', $crontab);
append_cronjob('* * * * * curl -s http://localhost/cron/test1.php');
append_cronjob('* * * * * curl -s http://localhost/cron/test2.php');
append_cronjob('* * * * * curl -s http://localhost/cron/test3.php');
回答by Sam T
I tried the solution below
我尝试了下面的解决方案
class Crontab {
// In this class, array instead of string would be the standard input / output format.
// Legacy way to add a job:
// $output = shell_exec('(crontab -l; echo "'.$job.'") | crontab -');
static private function stringToArray($jobs = '') {
$array = explode("\r\n", trim($jobs)); // trim() gets rid of the last \r\n
foreach ($array as $key => $item) {
if ($item == '') {
unset($array[$key]);
}
}
return $array;
}
static private function arrayToString($jobs = array()) {
$string = implode("\r\n", $jobs);
return $string;
}
static public function getJobs() {
$output = shell_exec('crontab -l');
return self::stringToArray($output);
}
static public function saveJobs($jobs = array()) {
$output = shell_exec('echo "'.self::arrayToString($jobs).'" | crontab -');
return $output;
}
static public function doesJobExist($job = '') {
$jobs = self::getJobs();
if (in_array($job, $jobs)) {
return true;
} else {
return false;
}
}
static public function addJob($job = '') {
if (self::doesJobExist($job)) {
return false;
} else {
$jobs = self::getJobs();
$jobs[] = $job;
return self::saveJobs($jobs);
}
}
static public function removeJob($job = '') {
if (self::doesJobExist($job)) {
$jobs = self::getJobs();
unset($jobs[array_search($job, $jobs)]);
return self::saveJobs($jobs);
} else {
return false;
}
}
}
}
credits to : Crontab Class to Add, Edit and Remove Cron Jobs
回答by Fred
This should do it
这应该做
shell_exec("crontab -l | { cat; echo '*/1 * * * * command'; } |crontab -");
回答by Alnitak
You could try overriding the EDITOR
environment variable with something like ed
which can take a sequence of edit commands over standard input.
您可以尝试EDITOR
使用类似的东西覆盖环境变量,ed
它可以在标准输入上执行一系列编辑命令。
回答by thedom
Depends where you store your crontab:
取决于您存储 crontab 的位置:
shell_exec('echo "'. $job .'" >> crontab');
回答by Ajie Kurniyawan
Nice...
Try this to remove an specific cron job (tested).
很好...
尝试删除特定的 cron 作业(已测试)。
<?php $output = shell_exec('crontab -l'); ?>
<?php $cron_file = "/tmp/crontab.txt"; ?>
<!-- Execute script when form is submitted -->
<?php if(isset($_POST['add_cron'])) { ?>
<!-- Add new cron job -->
<?php if(!empty($_POST['add_cron'])) { ?>
<?php file_put_contents($cron_file, $output.$_POST['add_cron'].PHP_EOL); ?>
<?php } ?>
<!-- Remove cron job -->
<?php if(!empty($_POST['remove_cron'])) { ?>
<?php $remove_cron = str_replace($_POST['remove_cron']."\n", "", $output); ?>
<?php file_put_contents($cron_file, $remove_cron.PHP_EOL); ?>
<?php } ?>
<!-- Remove all cron jobs -->
<?php if(isset($_POST['remove_all_cron'])) { ?>
<?php echo exec("crontab -r"); ?>
<?php } else { ?>
<?php echo exec("crontab $cron_file"); ?>
<?php } ?>
<!-- Reload page to get updated cron jobs -->
<?php $uri = $_SERVER['REQUEST_URI']; ?>
<?php header("Location: $uri"); ?>
<?php exit; ?>
<?php } ?>
<b>Current Cron Jobs:</b><br>
<?php echo nl2br($output); ?>
<h2>Add or Remove Cron Job</h2>
<form method="post" action="<?php $_SERVER['REQUEST_URI']; ?>">
<b>Add New Cron Job:</b><br>
<input type="text" name="add_cron" size="100" placeholder="e.g.: * * * * * /usr/local/bin/php -q /home/username/public_html/my_cron.php"><br>
<b>Remove Cron Job:</b><br>
<input type="text" name="remove_cron" size="100" placeholder="e.g.: * * * * * /usr/local/bin/php -q /home/username/public_html/my_cron.php"><br>
<input type="checkbox" name="remove_all_cron" value="1"> Remove all cron jobs?<br>
<input type="submit"><br>
</form>
回答by Dmitry Kireev
You can put your file to /etc/cron.d/ in cron format. Add some unique prefix to the filenaname To list script-specific cron jobs simply work with a list of files with a unique prefix. Delete the file when you want to disable the job.
您可以将文件以 cron 格式放入 /etc/cron.d/。向文件名添加一些唯一前缀 要列出特定于脚本的 cron 作业,只需使用具有唯一前缀的文件列表即可。当您要禁用该作业时,请删除该文件。
回答by Codemwnci
The easiest way is to use the shell_exec command to execute a bash script, passing in the values as parameters. From there, you can manipulate crontabs like you would in any other non-interactive script, and also ensure that you have the correct permissions by using sudo etc.
最简单的方法是使用 shell_exec 命令执行 bash 脚本,将值作为参数传递。从那里,您可以像在任何其他非交互式脚本中一样操作 crontab,并且还可以通过使用 sudo 等确保您拥有正确的权限。
See this, Crontab without crontab -e, for more info.
看到这个,没有 crontab -e 的 Crontab,了解更多信息。