I have a site on my webhotel I would like to run some scheduled tasks on. What methods of achieving this would you recommend?
What I’ve thought out so far is having
If you want to avoid setting up cron jobs and whatnot (though I'd suggest it's a better method), the solution you've provided is pretty good. On a number of projects, I've had the PHP script itself do the check to see whether it's time to run the update.
The down-side (okay, one of the down sides) is that if no one is using the app during a certain period then the script won't run.
The up-side is that if no one is using the app during a certain period then the script won't run. The tasks I've got it set up to do are things like "update a cache file", "do a daily backup" and whatnot. If someone isn't using the app, then you aren't going to need updated cache files, nor are there going to be any database changes to backup.
The only modification to your method which I'd suggest is that you only run those checks when someone successfully logs in. You don't need to check on every page load.
Cron is a general purpose solution for scheduling problems. But when you go big and schedules go high in frequency, there can be reliability/overlapping issues. If you see such problems, consider something like supervise or more sophisticated monit.
If you using cpanel u should add this like:
/usr/local/bin/php -q /home/yoursite/public_html/yourfile.php
I'm answering this now because no-one seems to have mentioned this exact solution.
On a site I'm currently working on, we've set up a cron job using cPanel, but instead of running the PHP Interpreter directly (because we're using CodeIgniter and our code is mapped to a controller function, this probably isn't a great idea) we're using wget
.
wget -q -O cron_job.log http://somehost/controller/method
-q
is so that wget won't generate any output (so you won't keep getting emails). -O cron_job.log
will save the contents of whatever your controller generates to a log file (overwritten each time so it won't keep growing).
I've found this to be the easiest way of getting 'proper' cron working.
If you want something more abstract, you might consider using something like a PHP scheduler. For example:
And also, to parse the cron expression, you could use an existing library such as https://github.com/mtdowling/cron-expression. It provides a lot of useful methods to help you figure out information of a cron job.
Hope that helps.
That's what cronjobs are made for. man crontab
assuming you are running a linux server. If you don't have shell access or no way to setup cronjobs, there are free services that setup cronjobs on external servers and ping one of your URLs.