python定时任务实现


一、安装 apscheduler

pip install apscheduler

二、实现定时任务

from apscheduler.schedulers.background import BackgroundScheduler
import utils.config as cf
from utils.mysqlOp import MySqlOp


def printhaoye(arg1, arg2):
    print(arg1+arg2)


if __name__ == '__main__':

    # 子进程中运行定时任务调度器
    scheduler = BackgroundScheduler()
    
	# 添加任务
    scheduler.add_job(

        # 指定任务
        printhaoye,

        # apscheduler.triggers.cron:当在特定时间定期运行 job 时使用
        # apscheduler.triggers.interval:当以固定的时间间隔运行 job 时使用
        # apscheduler.triggers.date:在某个特定时间仅运行一次 job 时使用
        trigger='interval',

        # 指定时间/时长 year、month、days、week、day_of_week、hour、minute、seconds、start_date、end_date
        seconds=2,

        # 方法传值
        args=['好', '耶'],

        # 指定id后
        # 可以通过 scheduler.remove_job('clear_log_job') 删除任务
        # 可以通过 scheduler.pause_job('clear_log_job') 暂停任务
        # 可以通过 scheduler.resume_job('clear_log_job') 恢复任务
        id='printhaoye_job'
    )

    # 启动定时任务【启动后仍然可以往里面添加任务】
    scheduler.start()

    # # 获取job列表
    # jobs = scheduler.get_jobs()
    # 打印格式化job列表
    scheduler.print_jobs()


    # 继续执行主任务
    # 主进程任务不结束,定时任务不结束
    # 主进程结束,定时任务自动终止
    import time
    time.sleep(10000)

三、运行结果

请添加图片描述


四、更详细的教程

一般定时任务使用上面的方法就够了,更复杂的定制需求可以参考这篇文章: https://www.bbsmax.com/A/qVdeOjLMJP/

猜你喜欢

转载自blog.csdn.net/weixin_43721000/article/details/129023825
今日推荐