How to set up a cron job via PHP (not CPanel)?
Once the PHP script is called for the first time by the crontab daemon, it can execute tasks in a time period that matches the logic of your application without keeping the user waiting. In this guide, you will create a sample cron_jobs database on an Ubuntu 20.04 server.
Most Linux systems with crond
installed provides a few directories you can set up jobs with:
/etc/cron.d/
/etc/cron.daily/
/etc/cron.weekly/
/etc/cron.monthly/
...
The idea here is to create a file in one of these directories. You will need to set the proper permissions/ownership to those (or one of those) directories so that the user launching the PHP script can write to it (Apache user if it's a web script, or whatever CLI user if CLI is used).
The easiest thing is to create an empty file, assign proper permission/ownership to it, and have the PHP script append/modify it.
Per example:
$ touch /etc/cron.d/php-crons
$ chown www-data /etc/cron.d/php-crons
Then in PHP:
$fp = fopen('/etc/cron.d/php-crons', 'a');
fwrite($fp, '* 23 * * * echo foobar'.PHP_EOL);
fclose($fp);
If what you're getting at is dynamically adding lots of jobs to crontab form your application, a better way to do that is manually add ONE cron job:
php -f /path/to/your/runner.php
Store your jobs that you would be adding to cron manually in a table (or one table per task-type), and then have your runner go through the table(s) every minute/hour/day/whatever and execute all the ones that should be executed at that time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With