首页 > 编程语言 > 详细

python中的轻量级定时任务调度库:schedule

时间:2020-03-30 09:48:23      阅读:70      评论:0      收藏:0      [点我收藏+]

1.1 schedule 基本使用

  1、schedule 介绍

      1. 提到定时任务调度的时候,相信很多人会想到芹菜celery,要么就写个脚本塞到crontab中。

      2. 不过,一个小的定时脚本,要用celery的话太“重”了。所以,我找到了一个轻量级的定时任务调度的库:schedule。

      3. 安装: pip install schedule

  2、schedule最基本使用

      官网地址:https://schedule.readthedocs.io/en/stable/ 

      参考博客:https://www.cnblogs.com/anpengapple/p/8051923.html 

技术分享图片
#! -*- coding:utf8 -*-
import schedule
import time

def job():
    print("I‘m working...")

schedule.every(1).seconds.do(job)
schedule.every(10).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)
schedule.every().monday.do(job)
schedule.every().wednesday.at("13:15").do(job)

while True:
    schedule.run_pending()
    time.sleep(1)
schedule最简单使用

      1. 这是在pypi上面给出的示例,通过这个栗子,我们也可以知道,schedule其实就只是个定时器。

      2. 在while True死循环中,schedule.run_pending()是保持schedule一直运行,去查询上面那一堆的任务,在任务中,就可以设置不同的时间去运行,跟crontab是类似的。

      3. 但是,如果是多个任务运行的话,实际上它们是按照顺序从上往下挨个执行的。如果上面的任务比较复杂,会影响到下面任务的运行时间

  3、利用python 用多线程/多进程 结合 schedule 实现异步定时任务

技术分享图片
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import schedule
import threading
import time


def job1():
    print("I‘m working for job1")
    time.sleep(2)
    print("job1:", datetime.datetime.now())


def job2():
    print("I‘m working for job2")
    time.sleep(2)
    print("job2:", datetime.datetime.now())


def job1_task():
    threading.Thread(target=job1).start()


def job2_task():
    threading.Thread(target=job2).start()


def run():
    schedule.every(1).seconds.do(job1_task)
    schedule.every(1).seconds.do(job2_task)

    while True:
        schedule.run_pending()
        time.sleep(1)
run()
利用python 用多线程/多进程 结合 schedule 实现异步定时任务
技术分享图片
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import schedule
import threading
import time

from lib.logs import Logger
from backends.syn_ldap_to_db import store_ldap_to_db


def syn_ldap_info():
    threading.Thread(target=store_ldap_to_db).start()


def crond_pre_employee():
    schedule.every().day.at("13:40").do(syn_ldap_info)
    # schedule.every(1).seconds.do(syn_ldap_info)
    # schedule.every(1).seconds.do(job2_task)
    while True:
        schedule.run_pending()
        time.sleep(1)

def run_cround():
    print ########################### run crond tasks ##############################
    now = time.strftime(%Y-%m-%d %H:%M:%S)
    msg = pre_staff中定时任务开始监控,时间【%s】 %now
    Logger().log(msg, True)
    threading.Thread(target=crond_pre_employee).start()

run_cround()
定时任务运用

 

python中的轻量级定时任务调度库:schedule

原文:https://www.cnblogs.com/jiaxinzhu/p/12596175.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!