Many times you are going to require some tasks that are not triggered by visitors in your website. These is a common scenario that you may find, and are extremely helpful.
Examples:
-
Renewals
-
Status checks
-
Garbage collectors
-
Notifications
-
…
Normally is stuff that you will like to do it from the CLI but in web development you end up doing something as:
wget “http://someurl.com/sendnewsletter”
Or
php -f /var/www/web1/somescript.php
I saw this grow till the infinite…and beyond
Well this has some very big problems.
-
Time Limit execution
-
Security, you may have security leaks if you expose the cron to the public
-
Code maintenance, separated from the rest of your app.
-
Cron maintenance, difficult to read
-
Code dependencies, yep if you use plain php…
-
Testing, how the hell do you test them?
-
Concurrency, what happens if one cron takes longer and overlaps the other?
I don’t know how many times I said to myself, this cron file one day is going to explode….since we had more than 100 lines of cron entries…so imagine to duplicate that in the staging server to test and later identify what does each cron.
Still I ask why developers and sysadmins don’t take more care of the cron file and add some comments and keep it clean and easy to read…
The 1 Line Cron
It may sound difficult but is not.
Why not having just 1 line in your cron that is executed let’s say every minute. This file will actually read from a table where we have the crons that we want to execute.
Imagine:
* * * * * /var/www/web1/cron.php
Will read the table cron where he will check the last execution and only execute it if it convenient. After the execution we can store the result, markt he cron as finished etc…
In this table we can use something like
-
id_cron
-
cron name (unique)
-
function to execute
-
schedule (* * * **)
-
last executed
-
executing (boolean)
-
activates (boolean)
Normally I use also a table called crontasks that is a table containing each of the executions with the output when started when finished the PID from linux..
I think you get me, now go and fix that CRON file!