Better way is to use cron. This is quite simple, although it may look intimidating at first:
Step 1 - Create a script that will be run by cron
For example, place this in <your-app-root>/cron.php:
<?php
$CRON_KEY = "some-random-value-here";
if ($_GET['key'] != $CRON_KEY) {
header(“HTTP/1.0 403 Forbidden”);
echo "You have no rights to access this page.";
exit();
}
// Your code here
Step 2 - Add crontab entry
To automatically execute your cron.php script, you can add a line like this to /etc/crontab:
## This will run each day at 2:30 AM
30 2 * * * www-data wget -O - -q http://yourdomain.com/cron.php?key=some-random-value-here &> /tmp/my-app-cron.log
..where some-random-value-here must match the random value placed in the PHP script. This is a security feature to prevent anybody from running your cron code.
Crontab line description
The first five parts of crontab line are: minutes, hours, day of month, month, day of week.
You can also use ranges, for example to run the script each day at 5, 7, 8, 12, 13, 14, 15, 20 you can use this:
0 5-8,12-15,20 * * * ...
You can also use "steps", for example to run every 5 minutes (suggested for recurrent jobs, such as indexing / cleanup tasks, etc):
*/5 * * * * ...
The sixth argument is the user that will be used to execute the command. You can use whichever user you want here, www-data, nobody, your user, etc. Best practice is to never use root here, unless really needed for some reason.
The remaining part of the line is the command that will be run at scheduled time.
The &> /tmp/my-app-cron.log part will make all the output from your latest cron.php execution to be stored inside /tmp/my-app-cron.log.
Read more..
For more information on cron usage, you can refer to crontab(5):
$ man 5 crontab
$hour = (int)date('G');, that script behavior is only to execute code in place of// my scriptonly in selected time ranges; this way you still have to manually execute the script (or use cron..), plus it doesn't guarantee code is executed once, etc.. So: using cron is the only reliable way to do this. Why don't you want to use it?