後台管理員設定開獎時間,到期自動從參與用戶中隨機抽取中獎者。技術棧:Java + Tomcat。
@Scheduled(需配合資料庫鎖防止叢集重複執行)。status=1 或建立臨時表),確保公平性。Collections.shuffle(list) 後取前 N 筆。@Scheduled(cron = "0 0 12 * * ?") // 每天中午 12 點執行
public void drawLottery() {
List candidates = userRepo.findByActivityIdAndStatus(activityId, 1);
Collections.shuffle(candidates);
List winners = candidates.subList(0, prizeCount);
winners.forEach(w => {
w.setWinner(true);
notificationService.send(w.getId(), "恭喜中獎!");
});
userRepo.saveAll(winners);
lotteryLogRepo.save(new LotteryLog(activityId, LocalDateTime.now(), winners.size()));
}
定時抽獎系統的核心在於「時間觸發可靠、隨機演算法公平、結果可追溯」。採用成熟排程框架與經典隨機演算法,即可快速落地穩健的抽獎服務。