当前位置: 代码网 > it编程>前端脚本>Python > 简单的Python定时后台任务实例

简单的Python定时后台任务实例

2026年09月23日 Python 我要评论
最近碰到个事情需要在flask启动的时候定时清理一些数据, 以前都是用的apscheduler, 但是这次的任务比较简单,定时上报一些请求信息, 不太想通过第三方包的方式进行操作, 看了一下threa

最近碰到个事情需要在flask启动的时候定时清理一些数据, 以前都是用的apscheduler, 但是这次的任务比较简单,定时上报一些请求信息, 不太想通过第三方包的方式进行操作, 看了一下threading源码,在提供thread主函数的同时, 还提供了一个timer的类,接下来就围绕这个timer来说明如何启动轻量定时任务

timer官方的说明

class timer(thread):
"""call a function after a specified number of seconds:
       t = timer(30.0, f, args=none, kwargs=none)
       t.start()
       t.cancel()     # stop the timer's action if it's still waiting
"""

大概意思就是:

函数会在你设定的时间后执行, 注意这里是只执行一次,所以没有达到我们想要的定时执行,我们结合flask server来演示下如何定时执行。

代码

import datetime
from flask import flask
import threading

app = flask(__name__)


def loop(msg):
    print(msg)
    timer = threading.timer(3, loop, (f"start check: {datetime.datetime.now()}",))
    timer.daemon = true
    timer.start()


@app.route("/")
def test():
   print("hello world")


if __name__ == '__main__':
    loop(f"start check: {datetime.datetime.now()}")
    app.run()

结果:

start check: 2022-06-15 10:31:56.069280
 * serving flask app 'test' (lazy loading)
 * environment: production
   warning: this is a development server. do not use it in a production deployment.
   use a production wsgi server instead.
 * debug mode: off
 * running on http://127.0.0.1:5000/ (press ctrl+c to quit)
start check: 2022-06-15 10:31:56.069321
start check: 2022-06-15 10:31:59.071218
start check: 2022-06-15 10:32:02.071914
start check: 2022-06-15 10:32:05.074362
start check: 2022-06-15 10:32:08.079799
start check: 2022-06-15 10:32:11.082420
start check: 2022-06-15 10:32:14.082753

存在的问题

当任务在定时时间内不能结束,那么在很短的时间内造成线程堆积,导致程序终止,所以我们进行改进。

改进

import datetime
import time
from flask import flask
import threading

app = flask(__name__)


def task():
    print(f"start check: {datetime.datetime.now()}")


def loop():
    # 使用while true的方式保持这个timer线程不停止
    while true:
        task()
        time.sleep(3)


@app.route("/")
def test():
    print("hello world")


if __name__ == '__main__':
    timer = threading.timer(3, loop)
    timer.daemon = true
    timer.start()
    app.run()

使用while true的方式保持这个timer线程不停止, 这样就只会有一个线程在后台执行,也不会造成线程堆积最终程序退出。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com