Information Systems often have tasks that should be done by schedule. This feature usually is needed because two reasons:
- because the task needs to be called at a specific moment;
- because the task is too long and it is impractible to take the user waiting while the task does not finish.
To provide this feature, we need help from a specific service. At Linux, for example, we have a service named "cron". Calling the commands below, it is possible to edit a file that specifies a list of commands to execute periodically:
$ contab -e
The "crontab" command uses the default text editor from the terminal. It can be specified by the environment variable "$EDITOR". To specify the commands and their periodicities, read the cron description.
One way to schedule task by a PHP application is creating a PHP script that can be executed by terminal (php-cli) and then you use the shedule service to specify the periodicity which the script should be called.
Although, there is a problem: this way the command will be called periodically. But some requirements do not want that the command is called periodically, but by schedule, that is a diferent stuff.
To do that, a viable way is creating a PHP script that will be responsable for run or not scheduled tasks from the application. This script can be specified at cron to be called daily or hourly (for example), and it could query the DB which tasks must be called. It is, to schedule a task, you would need to insert them in DB with the time you want the application execute them. The script would evaluate the tasks that was not called, it would call them, and then, update these records at DB to indicate they was already called (and it could also keep a text result of the executation). This script should have a way to call the correct methods, that can be in specific classes (for example: you could create an interface "schedule" that provide a method "cron" or "callScheduledTask").
Note that, if you have chosen a daily periodicity, your application should request only the date of the execution. And if you have chosen a hourly periodicity, your application can specify the date and time of execution.
Look at an example of a crontab generated file to execute a script hourly:
00 * * * * /usr/bin/php /directory/to/the/script.php