運(yùn)行文件:
<?php
/**
* 設(shè)置訂單狀態(tài)
*/
require_once dirname(__DIR__) . '/vendor/autoload.php';
require_once __DIR__ . '/lib/SetTradeStatus.php';
use Workerman\Worker;
use Workerman\Lib\Timer;
use think\DB;
$task = new Worker();
// 開啟多少個進(jìn)程運(yùn)行定時任務(wù),注意業(yè)務(wù)是否在多進(jìn)程有并發(fā)問題
$task->count = 1;
$task->onWorkerStart = function()
{
$SetTradeStatus = new SetTradeStatus();
Timer::add(1, [$SetTradeStatus, 'init'], [], false);
};
// 運(yùn)行worker
Worker::runAll();
類文件:
<?php
use think\DB;
class SetTradeStatus
{
private $trade_data;
public function init()
{
// 查詢訂單
$Trade = Db::name("trade");
// 所有訂單狀態(tài)為0的訂單
$Trade->where('trade_status', '0');
$data = $Trade->select();
foreach ($data as $key => $value) {
$this->handle_data($value);
}
}
private function handle_data($trade_data)
{
$this->trade_data = $trade_data;
// 設(shè)置訂單狀態(tài)
$this->set_trade_status();
// 發(fā)送設(shè)備通知
$this->add_msg();
}
private function set_trade_status()
{
DB::name('trade')->where('id', $this->trade_data['id'])->data('status', 1)->update();
}
private function add_msg()
{
$data = [
'trade_id' => $this->trade_data['id']
,'msg' -> 'OK'
];
Db::name('msg')->data($data)->insert();
}
}
類文件中, $this->trade_data 會被混淆么,
在執(zhí)行ID為1的數(shù)據(jù)的時候,trade_data 為1:;這個trade_data 會被下一次執(zhí)行的數(shù)據(jù)覆蓋么
不同的進(jìn)程之間 $this->trade_data 屬于不同的worker實(shí)例,互不影響;同一個進(jìn)程之內(nèi)按照你的代碼 foreach 那每次都在迭代覆蓋 $this->trade_data