Linux's crontab has always been a powerful tool for server operation and maintenance and business development. But when the number of scheduled tasks increases, management and migration become cumbersome and prone to problems. The following provides a crontab manager written in PHP, but you still need to add a call under crontab that executes once a minute to run this manager. Through this manager, you can achieve the following purposes:
It is not recommended that you use a database for crontab configuration management unless you can ensure that database requests can maintain a stable response for a long time. It is recommended to use nosql type cache storage and make persistent backups.
Without further ado, here’s the last piece of test code:
define('DS', DIRECTORY_SEPARATOR); requiredirname(__FILE__) . DS . 'vendor'. DS . 'autoload.php'; date_default_timezone_set('PRC'); error_reporting(E_ALL); $crontab_config= [ 'test_1'=> [ 'name'=> '服务监控1', 'cmd'=> 'php -v', 'output'=> '/tmp/test.log', 'time'=> '* * * * *' ], 'single_test'=> [ 'name'=> 'php -i', 'cmd'=> 'php -i', 'output'=> '/tmp/single_script.log', 'time'=> [ '* * * * *', '* * * * *', ], ], ]; $crontab_server= new\Jenner\Zebra\Crontab\Crontab($crontab_config); $crontab_server->start();
This code uses PHP's package manager composer. If you don't understand it, you can manually include the classes you need to use into your PHP script.
After running, we will view the crontab running record in the default log file (/var/log/php_crontab.log). Of course, you can specify the log file log by passing the second parameter to Crontab (make sure it is writable). The content of the log file is as follows:
[2014-11-10 19:50:08]-content:start. pid3778 [2014-11-10 19:50:08]-content:php -v [2014-11-10 19:50:08]-content:php -i [2014-11-10 19:50:08]-content:php -i [2014-11-10 19:50:08]-content:end. pid:3778
The log will record the program's startup time, running commands, pid and other information. Since I did it manually, the description is not exact 00 seconds. When it is officially used, add the following command to the crontab to realize the automatic operation of the manager.
* * * * * php php_crontab_manager.php
The jenner/multi_process package is a simple process control package. It is mainly used to use child processes to execute scheduled tasks, so that the parent process will not block and cause delays in scheduled tasks.
Project address:
This project is hosted on github and also provides packagist package support. You can add: "jenner/crontab" to composer.json: "1.0.0" to load this package.
The specific source code can be viewed on github.
Original article, please indicate when reprinting: Reprinted from Always Not Enough
Link address of this article: Crontab scheduled task management based on PHP