Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set cron job from php

Tags:

php

cron

I try To set cron job from php but every time i try the code blow it's not work. tell me what is the problem with this code

    $cron = $this->generator();
    file_put_contents("cron.txt", $cron);
    shell_exec('crontab cron.txt');

generator function make cron job string like below

12 1 * * * /usr/bin/sample >/dev/null 2>&1

the cron.txt file is fine. it contain the string but shell_exec some how not working

like image 426
Rome Avatar asked Jun 29 '26 08:06

Rome


2 Answers

Running your scrip with the hardcoded $corn locally works fine for me, i've included a couple of lines to clear the crontab in the beginning and couple of line to confirm the entry. see bellow.

$cron = '12 1 * * * /usr/bin/sample >/dev/null 2>&1';

file_put_contents('cron.txt', $cron);

shell_exec('crontab -r');
shell_exec('crontab cron.txt');

// To check the result
$output = []; 
exec('crontab -l',$output);
print_r($output);

Output:

Array
(
    [0] => 12 1 * * * /usr/bin/sample >/dev/null 2>&1
)

And here is a way to check the result of the crontab cron.txt execution:

$output = $return = [];
exec('crontab cron.txt',$output, $return);
var_dump($output, $return);

There will be no output nor return in case of success:

array(0) {
}
int(0)
like image 169
Ali Avatar answered Jun 30 '26 21:06

Ali


after many search in Dr Google i found out the answer i have to change the use to Apache user which is www-data so the command change to crontab -u www-data cron.txt

like image 23
Rome Avatar answered Jun 30 '26 23:06

Rome



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!