webman/process/Task2.php

76 lines
2.9 KiB
PHP

<?php
namespace process;
use app\dao\UserPhoneLogDao;
use App\Utils\API\SendCode;
use app\model\UserPhone;
use app\dao\UserRewardDao;
use support\Log;
use Workerman\Crontab\Crontab;
/**
* 查询用户是否在线类
*/
class Task2
{
public function onWorkerStart()
{
// 每5秒执行一次
new Crontab('0 */1 * * * *', function () {
$phones = UserPhone::where('created_at', '<', \Carbon\Carbon::now()->subMinutes(10))->where('status','!=',2)->get();
$start_time = time();
foreach ($phones as $key => $value) {
try {
// 获取用户的在线状态
$status = SendCode::get_ws_status($value->phone);
$currentTimestamp = time();
switch ($status) {
case 0: // 在线状态
if ($value->time > 3600) {
// 计算超过 1 小时的积分
$hours = intdiv($value->time, 3600);
$score = $hours * 20;
$remainingTime = $value->time % 3600;
// 更新用户积分和时长
$value->score += $score;
$value->day_score += $score;
$value->time = $remainingTime;
// 保存用户收益到 UserReward 表
UserRewardDao::Onhookincome($value->user_id, $score, $value->phone);
// 保存在线时长记录
UserPhoneLogDao::setOnlineTimeByPhone($value->phone, $status, $currentTimestamp);
}
// 更新在线时长
$value->status=1;
$value->time += $currentTimestamp - $value->last_time;
break;
case 1: // 不在线状态
$value->status = 0;
break;
case 3: // 账户不存在
$value->status = 2;
break;
}
// 更新用户最后活动时间和状态
$value->last_time = $currentTimestamp;
$value->save();
} catch (\Exception $e) {
// 记录错误日志,避免任务中断
Log::error("Error processing phone {$value->phone}: " . $e->getMessage());
}
}
$end_time = time();
Log::info("Task2: Processed " . count($phones) . " phones in " . ($end_time - $start_time) . " seconds");
});
}
}