This came up on a project I'm working on now but I've wondered about this in general. What methods are there for getting a PHP script to execute at regular intervals?
I can think of 3 ways.
1) Cron Job. I think some hosts will offer this service but not many. Exactly how it works I don't know - does it just pretend to be a visitor and call the required page? Is this offered a lot?
2) By hand. Visit an administration page every so often. Of course, this is tragically unreliable.
3) The only other way I can think of is to call a function on each page (or at least a common page or 2) which checks reads a value from a database/file/etc which contains the a timestamp of the last execution of the tasks. If the present time is both past the interval time (say 3:00am each day) and the timestamp is from before 3:00am on the current day (as it would be the first page load after 3:00am the previous day), then it saves a new timestamp and executes the tasks.
Could this still execute twice? Say there are 2 hits (visits A & 😎 very close together on a site with daily tasks. Could this happen?
A requests page.
B requests page.
A checks timestamp and time and decides it has to execute the tasks.
B checks timestamp and time and decides it has to execute the tasks.
A creates new timestamp, marking today's tasks as done.
B creates new timestamp, marking today's tasks as done.
A does the tasks.
B does the tasks and messes things up.
Could this happen? I'm minimized the chance of this happening by creating a new timestamp ASAP, before even doing the tasks, but there's still a window of opportunity.
I think the key is to ensure the new timestamp is written after checking before any other script checks. I'm sure there's some way where one script can "lock" the timestamp while it checks and (if necessary) updates and if another script checks, it finds the lock and waits until it's unlocked. However, the same problem occurs when updating the lock field but feel it adds a certain level of flexiblity.