I'm not entirely sure this is what you mean, but if you're trying to make a script that is only executed if the current time is 00:xx:xx, you can easily check for that:
if (date('G') == 0) {
// it is 00:00:00
} else {
// it is 01:00:00 or later
}
However, if what you want is a script that somehow, automagically becomes active one time when it's midnight, you can put this in an infinite while
loop:
set_time_limit(0);
$did_run = false;
while (true) {
if (date('G') == 0) {
// it is 00:00:xx (may not be exactly 00 seconds)
if (!$did_run) {
// the script hasn't run yet
$did_run = true; // to make sure it doesn't run a second time
// do stuff
} else {
// it is 00:00:xx but the script has already run
sleep(30); // wait 30 seconds before checking again
}
} else {
// it is 01:00:00 or later
$did_run = false; // so it will run again the next day
sleep(30); // wait 30 seconds before checking again
}
}
Note that once you start this script, it will never end unless you manually kill it (or it crashes). That is why this is not a good solution, the better option would be to use a cron job (on Linux/Unix servers) or scheduled task (on Windows servers).
Just create your script file as you normally would. Do not put any date/time checking in the script itself, because you're going to let the operating system handle that.
Then for Linux, log into your server via SSH and run crontab -e
, then add the following line:
0 0 * * * /usr/bin/php /path/to/my_script.php
This will tell the server to automatically run my_script.php
at roughly 00:00:00 every day. For more information about setting up cron jobs, the Ubuntu Community page has some useful information.
If your hosting provider uses a control panel like DirectAdmin or CPanel or something, it's possible that control panel offers you this option and you don't need to log in via SSH.
For Windows servers, you can log into the server via Remote Desktop and configure a scheduled task via the Task Scheduler. I'm not that experienced with that, so I'll point you to the TechNet page that documents how to do that. The task will need to call php.exe
with the full path to your script as an argument.
If you don't want to go to the trouble of setting this all up yourself, there are online solutions out there that call your script via a public URL every so often. One example is cron-job.org.