Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set up a cron job via PHP (not CPanel)?

Tags:

php

How to set up a cron job via PHP (not CPanel)?

like image 312
Alegotore Avatar asked Jan 22 '11 01:01

Alegotore


People also ask

Can cron run PHP script?

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.


2 Answers

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);
like image 181
netcoder Avatar answered Oct 21 '22 09:10

netcoder


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.

like image 21
scragz Avatar answered Oct 21 '22 09:10

scragz