Use PHP to create, edit and delete crontab jobs?

前端 未结 12 1505
余生分开走
余生分开走 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:09

    crontab command usage

    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/append provided 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.

提交回复
热议问题