I am searching for a way to run some code at specific time. Like at 4pm it run some logic and update my database. I googled and found that there are Cron (Linux module) and Scheduled Tasks (windows) to do this task. you can program and these utility will run your logic at desired time but i want to know that is there any thing available in PHP purely.
You need a long-running PHP process that sleep()
s for 60 seconds and checks if there is something to do at the current time()
.
If there is something to do: do it. Afterwards, sleep()
again in your endless loop.
The Cron daemon on Linux and the Scheduled Tasks service on Windows are system components that run continuously. They keep a list of jobs to run; each job is described by the time to run (repeatedly) and what command to run. There are other details on Windows but they are not relevant.
Neither the Cron daemon or the Scheduled Tasks service cares much about the command they run. If it is executable, they execute it.
The command you want to run at 4am is a PHP script that also must not care if it is executed by a shell (in a terminal window) or by the Cron or Scheduled Tasks.
It is possible to write a PHP script that takes the responsibilities of the Cron daemon but it is not recommended. There are a lot of unexpected situations you need to handle. From example, you have to implement a way to make sure it starts when the computer starts and it runs continuously. You have to make sure it doesn't skip the job scheduled for 4am and also that it doesn't run it twice. And so on, and so forth.
All these (apparently minor) things are already handled (and work properly) by the Cron daemon (on Linux) and the Scheduled Tasks service (on Windows). Use them if you can!
The only impediment on using these services provided by the OS is that you have to be an administrator on the server to create/update/delete their jobs.