How can I programmatically create a new cron job?

2019-01-05 08:53发布

I want to be able to programatically add a new cron job, what is the best way to do this?

From my research, it seems I could dump the current crontab and then append a new one, piping that back into crontab:

(crontab -l ; echo "0 * * * * wget -O - -q http://www.example.com/cron.php") | crontab -

Is there a better way?

标签: linux unix cron
16条回答
Evening l夕情丶
2楼-- · 2019-01-05 09:27

Simply change the editor to tee command:

export EDITOR="tee"
echo "0 * * * * /bin/echo 'Hello World'" | crontab -e
查看更多
唯我独甜
3楼-- · 2019-01-05 09:28
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;
}

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;
}

    append_cronjob('* * * * * curl -s http://localhost/cron/test.php');
查看更多
成全新的幸福
4楼-- · 2019-01-05 09:28

This would check to ensure that your command doesn't already exist before adding it.

crontab -l 2>/dev/null | grep -q '/path/to/script' || echo "5 * * * * /path/to/script" | crontab -

Cheers.

查看更多
混吃等死
5楼-- · 2019-01-05 09:31

It's always worked well for me.

You should consider a slightly more sophisticated script that can do three things.

  1. Append a crontab line; assuring that it didn't exist. Adding when it already exists is bad.

  2. Remove the crontab line. Perhaps only warning if it didn't exist.

  3. A combination of the above two features to replace the crontab line.

查看更多
手持菜刀,她持情操
6楼-- · 2019-01-05 09:31

The best way if you're running as root, is to drop a file into /etc/cron.d

if you use a package manager to package your software, you can simply lay down files in that directory and they are interpreted as if they were crontabs, but with an extra field for the username, e.g.:

Filename: /etc/cron.d/per_minute

Content: * * * * * root /bin/sh /home/root/script.sh

查看更多
孤傲高冷的网名
7楼-- · 2019-01-05 09:39

Piping stdout into crontab didn't install the new crontab for me on macOS, so I found this solution instead, using the tee editor in a sub shell:

(EDITOR=tee && (crontab -l ; echo "@daily ~/my-script.sh" ) | uniq - | crontab -e)
查看更多
登录 后发表回答