Skip to content

Writing batch (CLI) scripts

szeber edited this page Jun 13, 2012 · 8 revisions

When writing batch scripts, it's usually a good idea to provide usage instructions and a basic help for the script. For this reason the framework provides a CliUserInterfaceHelper class.

The entry point for the batch scripts should include the batch's bootstrap, which should parse the -e option if it's used to determine the running environment. It should also contain a class that extends either \YapepBase\Batch\BatchScript or \YapepBase\Batch\LockingBatchScript. In the end it should instantiate the class and call it's run() method. The run() method handles any exceptions, and dispatches the \YapepBase\Event\Event::TYPE_APPSTART and \YapepBase\Event\Event::TYPE_APPFINISH events.

Normal scripts

Normal batch scripts are usually run manually, or run as scheduled (cron) jobs, but may run in 2 instances at the same time. If the script may not run in parallel instances a locking script is recommended (see below). The base class defines the --help switch for displaying the usage of the script with all defined switches, and the -e switch for defining the running environment. The -e switch should be parsed by the bootstrap file.

For these scripts the entry point class should extend the \YapepBase\Batch\BatchScript class.

Locking scripts

Locking batch scripts ensure that the script runs in at most one instance on the same host. They ensure this by creating lock files. The lock file is by default created at /var/run, but this can be configured with the --pid-path command line switch, or the system.path.batchPid configuration option. The pid file's name can be set with the --pid-file switch. If the file name is not specified in a switch, it defaults to the name of the script without the .php suffix. With the --help switch the usage of the script will be printed. The -e switch is also defined for setting the current environment, but this option should be parsed by the bootstrap file before starting the script's application code.

For these scripts the entry point class should extend the \YapepBase\Batch\LockingBatchScript class.

Signal handling

To receive process control signals, the script's entry point's first PHP code line should be declare(ticks = 1); or the signal handler will not receive the signals correctly. In the default implementation the following signals are received by the script:

  • SIGTERM
  • SIGHUP
  • SIGINT

All of them will call the abort() method which should gracefully stop the script's execution. If you implement an empty abort() method, or the abort method does not stop execution, the script will not react to CTRL-C, kill, only to kill -KILL.

Clone this wiki locally