告别凌晨 8 点发送报表

Python   2025-12-03 10:52   50   0  
#!/usr/bin/env python3
"""
每日8点重置脚本 - 比闹钟还准时的自动化管家
"""

class DailyResetManager:
    def __init__(self):
        self.redis = redis.Redis(host='localhost', port=6379, db=0)
        self.mysql = pymysql.connect(host='localhost', user='root', 
                                   password='password', database='music_app')

    def run_daily_reset(self):
        """主要重置流程"""
        print("🌅 新的一天开始了,开始重置大作战...")

        try:
            # 1. 统计昨天的数据
            yesterday_stats = self.get_yesterday_stats()
            print(f"📊 昨天数据统计:{yesterday_stats}")

            # 2. 备份重要数据
            backup_success = self.backup_critical_data()
            print(f"💾 数据备份:{'成功' if backup_success else '失败'}")

            # 3. 清理缓存
            cleared_caches = self.clear_user_caches()
            print(f"🧹 清理了 {cleared_caches} 个用户缓存")

            # 4. 重置用户听歌时长
            reset_users = self.reset_user_durations()
            print(f"🔄 重置了 {reset_users} 个用户的听歌时长")

            # 5. 清理过期数据
            cleaned_records = self.clean_expired_data()
            print(f"🗑️ 清理了 {cleaned_records} 条过期记录")

            # 6. 发送统计报告
            self.send_daily_report(yesterday_stats, reset_users)
            print("📧 日报已发送给老板")

            print("✅ 重置完成,今天又是美好的一天!")

        except Exception as e:
            print(f"❌ 重置过程出错: {e}")
            self.send_error_alert(str(e))

    def clear_user_caches(self):
        """批量清理用户缓存"""
        patterns = [
            'user_state_*',
            'user_vip_status_*', 
            'earned_score_*',
            'behavior_pattern_*'
        ]

        cleared_count = 0
        for pattern in patterns:
            keys = self.redis.keys(pattern)
            if keys:
                self.redis.delete(*keys)
                cleared_count += len(keys)

        return cleared_count

    def reset_user_durations(self):
        """重置用户听歌时长"""
        reset_time = int(time.time())
        today = datetime.now().strftime('%Y-%m-%d')

        cursor = self.mysql.cursor()
        sql = """
        UPDATE fa_user 
        SET today_listen_duration = 0,
            last_reset_time = %s,
            last_listen_date = %s
        WHERE today_listen_duration > 0
        """

        cursor.execute(sql, (reset_time, today))
        affected_rows = cursor.rowcount
        self.mysql.commit()
        cursor.close()

        return affected_rows

    def send_daily_report(self, stats, reset_users):
        """发送日报给老板"""
        report = f"""
        📈 音乐APP日报 ({datetime.now().strftime('%Y-%m-%d')})

        昨日数据:
        - 活跃用户:{stats.get('active_users', 0)} 人
        - 总听歌时长:{stats.get('total_duration', 0)} 分钟
        - 积分发放:{stats.get('total_score', 0)} 分

        系统状态:
        - 重置用户:{reset_users} 人
        - 系统状态:正常 ✅
        - CPU使用率:10% (很轻松)

        今日预测:
        - 预计活跃用户:{stats.get('active_users', 0) * 1.1:.0f} 人
        - 服务器压力:无压力 😎
        """

        # 发送到企业微信/钉钉
        self.send_to_work_chat(report)