

实现过程
一、导入必要的库
import pymysqlimport timefrom datetime import datetime, timedeltaimport schedule
pymysql.connect()创建数据库连接,并使用上下文管理器确保连接正确关闭。UPDATE SQL语句来更新指定记录。def update_record(db, table, column, value, condition):try:with pymysql.connect(host='localhost', user='root', password='', db=db) as conn:with conn.cursor() as cursor:sql = f"UPDATE {table} SET {column} = %s WHERE {condition}"cursor.execute(sql, (value,))conn.commit()print(f"{datetime.now()}: Updated record in {table}")except Exception as e:print(f"Failed to update record: {e}")
schedule.every().day.at("23:00").do(...)安排update_record函数在每天23:00时运行,传入所需的参数。def setup_daily_update():# 设置每天晚上11点执行的任务schedule.every().day.at("23:00").do(update_record, "mydb", "users", "status", "active", "id = 1")
初始化:
setup_daily_update()函数配置定时任务。无限循环:
while True:创建一个无限循环,使程序持续运行。schedule.run_pending()检查是否有任何待执行的任务。time.sleep(1)让程序暂停1秒钟,减少CPU占用,同时保持对定时任务的响应性。if __name__ == "__main__":setup_daily_update()print("Scheduler started. Waiting for the next scheduled task...")while True:schedule.run_pending()time.sleep(1) # 等待1秒后再检查是否有待执行的任务
以上就是本次分享的全部内容,如果你有任何疑问或想要分享你的自动化办公经验,我们的评论区永远为你敞开。你的每一个点赞和转发,都是对我们最大的支持和鼓励!
想要深入学习并获取文中的完整代码吗?很简单,关注我们的公众号,并回复文章标题,即可立即获取。
再次感谢你的阅读,期待在下一次分享中与你相见!
精选阅读
python自动化系列:将Excel表格中的学生信息自动填充到一个word文档
python自动化系列:将Excel表格中的学生多条信息自动填充到一个Word文档
python自动化系列:Python脚本实现GIF动画的快速生成