Reputation: 558
I had found a script that supposedly schedules a script to execute. I am very new to PHP and I do NOT want to use cron. Here's the script I found:
<?php
$hour = date('G');
$day = date('N'); // 1..7 for Monday to Sunday
if (($hour >= 5 && $hour <= 7) // 5am - 7am
|| ($hour >= 10 && $hour <= 12) // 10am - 12 noon
|| ($hour >= 15 && $hour <= 19) // 3pm - 7pm
|| ($day == 5) // Friday
) { ?>
//my script
<?php } ?>
Because I know so little, If I put my script where it says, would it execute at that certain time every time that happens? Thank you in advance! -Ben
Upvotes: 1
Views: 1446
Reputation: 6777
Better way is to use cron. This is quite simple, although it may look intimidating at first:
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
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.
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
.
For more information on cron usage, you can refer to crontab(5)
:
$ man 5 crontab
Upvotes: 4