Use PHP to create, edit and delete crontab jobs?

前端 未结 12 1318
余生分开走
余生分开走 2020-11-22 06:54

Is it possible to use PHP to create, edit and delete crontab jobs?

I know how to list the current crontab jobs of the Apache user:

$output = shell_ex         


        
12条回答
  •  鱼传尺愫
    2020-11-22 07:12

    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

    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

    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');
    

提交回复
热议问题