0

I found the following on stackoverflow but was wondering how to change this so I can append and delete a specific cron job. Also was wondering how this would interplay with cron jobs set up through Cpanel on a shared host?

$cron_file = 'cron_filename';
// Create the file
touch($cron_file); 
// Make it writable
chmod($cron_file, 0777); 
// Save the cron
file_put_contents($cron_file, '* * * * * your_command'); 
// Install the cron
exec('crontab cron_file');
Vadim Kotov
  • 7,103
  • 8
  • 44
  • 57
DCR
  • 10,658
  • 7
  • 38
  • 86
  • I think you'd be much better off setting up touch file switches or some other means to check if the cron line is allowed to run. If you're trying to do something like `cp /your/file /your/backup/file`, put it in a shell script. – Jared Farrish Apr 13 '17 at 13:25
  • I don't understand what you mean – DCR Apr 13 '17 at 13:28
  • If you're writing to crontab, that sounds like you're doing something wrong. I've never even thought of what you're describing, and I've written probably a hundred cronjobs. So if you're trying to control whether the "your_command" part runs by adding/removing it from the crontab file, I would suggest writing a bash script `./your_command_script.sh` and within there check for the presence of a file that tells you whether or not the cron script can run, and write/delete that file from your application. If you're not trying to do that, explain why you're trying to write directly to crontab. – Jared Farrish Apr 13 '17 at 13:49
  • Based on user interaction on my website I want to be able to turn on a cron job that runs every hour. With additional interaction on website I want to be able to turn off the cron job. I have other cron jobs running independently on the website. This is in a shared hosting environment so may be a mute point as I'm not sure if it's possible to control cron jobs outside of Cpanel. (Bluehost) – DCR Apr 13 '17 at 14:24
  • [`touch()`](http://php.net/manual/en/function.touch.php) and [`unlink()`](http://php.net/manual/en/function.unlink.php) can be used in your PHP application to write a tmp file: `touch('/tmp/cron_switches/your_command.run')` and `unlink('/tmp/cron_switches/your_command.run')`. Then in a bash script you use for your cronjob, you can: `if [ -f '/tmp/cron_switches/your_command.run' ]; then '/path/to/your/cron/scripts/your_command' fi` Then in crontab: `* * * * * /path/to/your/cron/scripts/your_command.sh` Note the last is a shell executable. – Jared Farrish Apr 13 '17 at 15:00
  • Note that `touch()` will create the file if it doesn't exist, hence why I'm using it here. – Jared Farrish Apr 13 '17 at 15:04
  • There's also this: http://stackoverflow.com/q/4421020/451969 And checkout Packagist for the packages that allow you to manage cronjobs outside of crontab: https://packagist.org/search/?q=crontab&orderBys%5B0%5D%5Bsort%5D=downloads&orderBys%5B0%5D%5Border%5D=desc – Jared Farrish Apr 13 '17 at 15:08

0 Answers0