You have 3 options. My recommendation: Use cron if you can, user driven if you have to, and daemon as a last resort.
(1) cron (as mentioned in comments)
cron is a scheduler for linux systems that will run a command line job on your system. You log into your server over ssh, type crontab -e
, and add a line like this:
4 5 * * * php /path/to/my/script.php
This would run the script at 5:04 a.m. every day.
<?php
// /path/to/my/script.php
// Do something
Some hosting services allow entering cron jobs with a GUI. There are also external cron services, that will call a URL for you at specific times.
(2) daemon
This is the most advanced option and also the least reliable: You run a command line script that contains an infinite loop. The script then periodically checks state and responds to it. Because it is likely to crash after months of running, you have to have a second script to restart it in case it does. This is a lot of work, but it is the most flexible approach.
<?php
while (1) {
// fetch $last_exec_timestamp from database
if ($last_exec_timestamp < time() + 86400) {
// set last_exec_timestamp to now in database
// do something
}
sleep(5);
}
3. user driven
If you have a decent amount of traffic on your site, you can simply include a the job this in your page footer, when there is no more output. Make sure this code is fast, or an unlucky user will be waiting for it.
<?php
// fetch $last_exec_timestamp from database
if ($last_exec_timestamp < time() + 86400) {
// set last_exec_timestamp to now in database
// do something
}
There are also to more fancy approaches of "user driven" that I haven't personally tested in another stack overflow question.