php定時執行任務(定時刪除用戶過時積分)

最近網站實行用戶積分過時制度,只保留用戶近三月積分,三月前未使用積分進行扣除
*平臺用戶量比較大,感受這樣作會出問題,有沒有好的解決方法?(windows iis服務器)
代碼以下:sql

ignore_user_abort(); 
set_time_limit(0); 
do{
    $this->del_score();
    sleep(24*3600);
}while (true);

private function del_score()
{
    $date = to_date(to_timespan(to_date(TIME_UTC)." -3 month"),'Y-m-d');
    
    // 近三月使用積分
    $user_scores = $GLOBALS['db']->getAll("SELECT user_id,sum(score) as score FROM ".DB_PREFIX."user_score_log WHERE score<0 AND create_time_ymd > '".$date."' GROUP BY user_id");
    
    // 扣除用戶過時積分
    $update_sql = "UPDATE ".DB_PREFIX."user SET score = score - CASE id ";

    // 添加過時積分扣除日誌
    $insert_sql = "INSERT INTO ".DB_PREFIX."user (`user_id`, `score`, `account_score`, `mome`, `type`, `create_time`, `create_time_ymd`, `create_time_ym`, `create_time_y`) VALUES ";

    foreach ($user_scores as $k => $v) {
        // 總過時積分
        $old_account_score = $GLOBALS['db']->getOne("SELECT account_score FROM ".DB_PREFIX."user_score_log WHERE user_id=".$v['user_id']." AND create_time_ymd<=".$date." ORDER BY id DESC LIMIT 1");
        if($old_account_score > abs($v['score'])) // 過時積分未消費完
        {
            $arr[$v['user_id']] = $v['score'];

            // 應扣除積分
            $score = intval($account_score - abs($v['score']));
            $update_sql .= sprintf("WHEN %d THEN %d ", $v['user_id'], $score);

            // 帳戶現有積分
            $account_score = $GLOBALS['db']->getOne("SELECT score - {$score} FROM ".DB_PREFIX."user WHERE id=".$v['user_id']);
            $create_time = TIME_UTC;
            $create_time_ymd = to_date(TIME_UTC,"Y-m-d");
            $create_time_ym = to_date(TIME_UTC,"Ym");
            $create_time_y = to_date(TIME_UTC,"Y");
            $insert_sql .= "(".$v['user_id'].",-".$score.",".$account_score.",'積分到期未使用部分扣除',26,".$create_time.",'".$create_time_ymd."','".$create_time_ym."','".$create_time_y."'),";
        }
        continue; 
    }
    $ids = implode(',', array_keys($arr)); 
    $update_sql .= " END WHERE id IN ($ids)";
    $insert_sql = substr($insert_sql, 0, -1);
    $GLOBALS['db']->query($update_sql);
    $GLOBALS['db']->query($insert_sql);
}
相關文章
相關標籤/搜索