Скачать рабочий человек
Скачать рабочий человек
Скачать workman/mysql
Скачать workman/mysql
1. Функция синхронизации является анонимной функцией (закрытие)
use \Workerman\Worker; use \Workerman\Lib\Timer; require_once './Workerman/Autoloader.php'; $task = new Worker(); // How many processes to start running timed tasks, pay attention to the problem of multi-process concurrency $task->count = 1; $task->onWorkerStart = function($task) { // Execute every 2.5 seconds $time_interval = 2.5; Timer::add($time_interval, function() { echo "task run\n"; }); }; // Running worker Worker::runAll();
2. Функция синхронизации является общей функцией
require_once './Workerman/Autoloader.php'; use \Workerman\Worker; use \Workerman\Lib\Timer; // Ordinary functions function send_mail($to, $content) { echo "send mail ...\n"; } $task = new Worker(); $task->onWorkerStart = function($task) { $to = '[email protected]'; $content = 'hello workerman'; // After 10 seconds, the sending mail task is executed, and the last parameter passes false, indicating that only once is run. Timer::add(10, 'send_mail', array($to, $content), false); }; // Running worker Worker::runAll();
3. Способ классификации временных функций
require_once './Workerman/Autoloader.php'; use \Workerman\Worker; use \Workerman\Lib\Timer; class Mail { // Note that the callback function property must be public public function send($to, $content) { echo "send mail ...\n"; } } $task = new Worker(); $task->onWorkerStart = function($task) { // Send an email in 10 seconds $mail = new Mail(); $to = '[email protected]'; $content = 'hello workerman'; Timer::add(10, array($mail, 'send'), array($to, $content), false); }; // Running worker Worker::runAll();
4. Функция синхронизации-это метод класса (таймер используется внутри класса)
require_once './Workerman/Autoloader.php'; use \Workerman\Worker; use \Workerman\Lib\Timer; class Mail { // Note that the callback function property must be public public function send($to, $content) { echo "send mail ...\n"; } public function sendLater($to, $content) { // The callback method belongs to the current class, and the first element of the callback array is $this. Timer::add(10, array($this, 'send'), array($to, $content), false); } } $task = new Worker(); $task->onWorkerStart = function($task) { // Send an email in 10 seconds $mail = new Mail(); $to = '[email protected]'; $content = 'hello workerman'; $mail->sendLater($to, $content); }; // Running worker Worker::runAll();
5. Статические методы с функциями синхронизации в качестве классов
require_once './Workerman/Autoloader.php'; use \Workerman\Worker; use \Workerman\Lib\Timer; class Mail { // Note that this is a static method, and the callback function property must also be public. public static function send($to, $content) { echo "send mail ...\n"; } } $task = new Worker(); $task->onWorkerStart = function($task) { // Send an email in 10 seconds $to = '[email protected]'; $content = 'hello workerman'; // Static methods of calling classes on time Timer::add(10, array('Mail', 'send'), array($to, $content), false); }; // Running worker Worker::runAll();
6. Статические методы (с пространствами имен) с временными функциями в качестве классов
namespace Task; require_once './Workerman/Autoloader.php'; use \Workerman\Worker; use \Workerman\Lib\Timer; class Mail { // Note that this is a static method, and the callback function property must also be public. public static function send($to, $content) { echo "send mail ...\n"; } } $task = new Worker(); $task->onWorkerStart = function($task) { // Send an email in 10 seconds $to = '[email protected]'; $content = 'hello workerman'; // Timely calls to static methods of classes with namespaces Timer::add(10, array('\Task\Mail', 'send'), array($to, $content), false); }; // Running worker Worker::runAll();
7. Уничтожьте текущее время в таймере (передайте $timer_id с помощью закрытия)
use \Workerman\Worker; use \Workerman\Lib\Timer; require_once './Workerman/Autoloader.php'; $task = new Worker(); $task->onWorkerStart = function($task) { // count $count = 1; // To properly pass $timer_id inside the callback function, $timer_id must be preceded by an address character.& $timer_id = Timer::add(1, function()use(&$timer_id, &$count) { echo "Timer run $count\n"; // Destroy the current timer after 10 runs if($count++ >= 10) { echo "Timer::del($timer_id)\n"; Timer::del($timer_id); } }); }; // Running worker Worker::runAll();
8. Уничтожьте текущее время в таймере (передайте $timer_id по параметру)
require_once './Workerman/Autoloader.php'; use \Workerman\Worker; use \Workerman\Lib\Timer; class Mail { public function send($to, $content, $timer_id) { // Temporarily add a count attribute to the current object to record the number of times the timer runs $this->count = empty($this->count) ? 1 : $this->count; // Destroy the current timer after 10 runs echo "send mail {$this->count}...\n"; if($this->count++ >= 10) { echo "Timer::del($timer_id)\n"; Timer::del($timer_id); } } } $task = new Worker(); $task->onWorkerStart = function($task) { $mail = new Mail(); // To properly pass $timer_id inside the callback function, $timer_id must be preceded by an address character.& $timer_id = Timer::add(1, array($mail, 'send'), array('to', 'content', &$timer_id)); }; // Running worker Worker::runAll();
9. Установка таймеров только в определенных процессах
Рабочий экземпляр имеет четыре процесса и устанавливает таймеры только для процессов с идентификатором 0.
use Workerman\Worker; use Workerman\Lib\Timer; require_once './Workerman/Autoloader.php'; $worker = new Worker(); $worker->count = 4; $worker->onWorkerStart = function($worker) { // Timers are only set on processes with ID number 0, but not on other processes 1, 2 and 3. if($worker->id === 0) { Timer::add(1, function(){ Echo "4 worker processes, only set timer\n" in process 0; }); } }; // Running worker Worker::runAll();
Пример
Поставки. PHP используется для написания временных задач
onWorkerStart = function ($task) { global $db, $redis; $db = new \Workerman\MySQL\Connection('127.0.0.1', '3306', 'root', 'root', 'test'); $redis = new Redis(); $redis->connect('127.0.0.1', 6379); $redis->auth("qqq123123."); $time_interval = 0.1; Timer::add($time_interval, function () { global $db, $redis; $insert['name'] = 123; $db->insert('shipments')->cols($insert)->query(); // sleep(100); }); }; function curlGet($url = '', $options = []) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 30); if (!empty($options)) { curl_setopt_array($ch, $options); } // HTTPS requests do not validate certificates and hosts curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $data = curl_exec($ch); curl_close($ch); return $data; } function newGetOrderInfo($taobao, $orderId) { $taobao = urlencode($taobao); $url = "http://114.55.144.79/taobao/TradeFullinfoGetRequest.php?shop=$taobao&tid=$orderId"; $json = curlGet($url); return json_decode($json, true)['trade']; } Worker::runAll();
Выше приведено все содержание этой статьи. Я надеюсь, что это будет полезно для изучения каждого, и я надеюсь, что вы будете больше поддерживать разработчика.