How to check if cronjob exists with PHP?
Is there a way to know if a cronjob already exists wit开发者_如何学Goh php?
I want it to work on most hostings, even shared.
NO, There's no such direct privilege in PHP.
But (On Dedicated Server) you can write a PHP script to read /etc/crontab
file and parse the info to check if a specific cron exists on the server.
You could try running the crontab -l
command, which should work from PHP. You might have to qualify the full path, e.g., /usr/bin/crontab -l
, which would depend on the host.
This will return the crontab entries for the user who runs the command, which is what you want if the PHP page and cron jobs run as the same user (many shared hosts use setuid php scripts these days). To get the crontab entries for another user you'd need superuser rights on most systems, and crontab -l -u otheruser
.
using shell_exec()
or system()
or something like that might solve the problem.
But it won't work with safe_mode
turned on.
and i think shared hostings won't have these features enabled.
@Nathan: wouldn't /usr/bin/crontab -l
be returning the crontab for the user who runs the script? e.g. www-data, wwwrun, apache or something?
In addition to Nathan's answer:
If you can run exec()
and the crontab
command
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;
}
$command = '30 9 * * * '.__DIR__.'/cronjobs/job1.php';
if(cronjob_exists($command)===FALSE){
//add job to crontab
exec('echo -e "`crontab -l`\n'.$command.'" | crontab -');
}
精彩评论