1.安装

pip install schedule

2.文档

https://schedule.readthedocs.io/en/stable/faq.html#how-to-execute-jobs-in-parallel

3.官网使用demo

import schedule
import time def job():
print("I'm working...") schedule.every(10).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)
schedule.every(5).to(10).minutes.do(job)
schedule.every().monday.do(job)
schedule.every().wednesday.at("13:15").do(job)
schedule.every().minute.at(":17").do(job) while True:
schedule.run_pending()
time.sleep(1)

4.我的schedule使用demo

import sys
import time
import schedule
import os
import logging
if not os.path.exists('/var/log/video_download/'):
os.makedirs('/var/log/video_download')
log = logging.getLogger()
log.setLevel(logging.DEBUG)
fmt = logging.Formatter("%(asctime)s %(pathname)s %(filename)s %(funcName)s %(lineno)s %(levelname)s - %(message)s",
"%Y-%m-%d %H:%M:%S")
stream_handler = logging.FileHandler(
'/var/log/video_download/debug-%s.log' % (time.strftime('%Y-%m-%d', time.localtime(time.time()))))
stream_handler.setLevel(logging.DEBUG)
stream_handler.setFormatter(fmt)
log.addHandler(stream_handler)
def handler():
print("this is handler")
def main():
if len(sys.argv) != 2:
print('python video_data.py hour')
sys.exit()
param = sys.argv[1]
if param == 'hour':
log.debug("enter main")
schedule.every().day.at("00:00").do(handler)
schedule.every().hour.do(handler)
while True:
schedule.run_pending()
time.sleep(1)
else:
print("python video_data.py hour")
sys.exit() if __name__ == "__main__":
main()

5.拓展:

  并行执行任务

  (1)默认情况下,schedule按顺序执行所有作业。这背后的原因是很难找到一个让每个人都开心的并行执行模型

import threading
import time
import schedule def job():
print("I'm running on thread %s" % threading.current_thread()) def run_threaded(job_func):
job_thread = threading.Thread(target=job_func)
job_thread.start() schedule.every(10).seconds.do(run_threaded, job)
schedule.every(10).seconds.do(run_threaded, job)
schedule.every(10).seconds.do(run_threaded, job)
schedule.every(10).seconds.do(run_threaded, job)
schedule.every(10).seconds.do(run_threaded, job) while 1:
schedule.run_pending()
time.sleep(1)

  (2)如果需要控制线程数,就需要用queue

import Queue
import time
import threading
import schedule def job():
print("I'm working") def worker_main():
while 1:
job_func = jobqueue.get()
job_func()
jobqueue.task_done() jobqueue = Queue.Queue() schedule.every(10).seconds.do(jobqueue.put, job)
schedule.every(10).seconds.do(jobqueue.put, job)
schedule.every(10).seconds.do(jobqueue.put, job)
schedule.every(10).seconds.do(jobqueue.put, job)
schedule.every(10).seconds.do(jobqueue.put, job) worker_thread = threading.Thread(target=worker_main)
worker_thread.start() while 1:
schedule.run_pending()
time.sleep(1)

  (3)抛出异常

import functools

def catch_exceptions(cancel_on_failure=False):
def catch_exceptions_decorator(job_func):
@functools.wraps(job_func)
def wrapper(*args, **kwargs):
try:
return job_func(*args, **kwargs)
except:
import traceback
print(traceback.format_exc())
if cancel_on_failure:
return schedule.CancelJob
return wrapper
return catch_exceptions_decorator @catch_exceptions(cancel_on_failure=True)
def bad_task():
return 1 / 0 schedule.every(5).minutes.do(bad_task)

  (4)只运行一次

def job_that_executes_once():
# Do some work ...
return schedule.CancelJob schedule.every().day.at('22:30').do(job_that_executes_once)

  (5)一次取消多个任务

def greet(name):
print('Hello {}'.format(name)) schedule.every().day.do(greet, 'Andrea').tag('daily-tasks', 'friend')
schedule.every().hour.do(greet, 'John').tag('hourly-tasks', 'friend')
schedule.every().hour.do(greet, 'Monica').tag('hourly-tasks', 'customer')
schedule.every().day.do(greet, 'Derek').tag('daily-tasks', 'guest') schedule.clear('daily-tasks')

  (6)在任务中加入日志功能

import functools
import time import schedule # This decorator can be applied to
def with_logging(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print('LOG: Running job "%s"' % func.__name__)
result = func(*args, **kwargs)
print('LOG: Job "%s" completed' % func.__name__)
return result
return wrapper @with_logging
def job():
print('Hello, World.') schedule.every(3).seconds.do(job) while 1:
schedule.run_pending()
time.sleep(1)

  (7)随机开展工作

def my_job():
# This job will execute every 5 to 10 seconds.
print('Foo') schedule.every(5).to(10).seconds.do(my_job)

  (8)传参给作业函数

def greet(name):
print('Hello', name) schedule.every(2).seconds.do(greet, name='Alice')
schedule.every(4).seconds.do(greet, name='Bob')

python:定时任务模块schedule的更多相关文章

  1. python的定时任务模块--schedule

    首先先安装一下模块 下面我们简单的学习一下schedule模块 先简单的看个示例 import schedule def test(*args,**kwargs): print("hello ...

  2. 定时任务模块 schedule

    # coding:utf-8 from learning_python.Telegram_push.check_hardware import check_cpu import schedule im ...

  3. python定时任务模块APScheduler

    一.简单任务 定义一个函数,然后定义一个scheduler类型,添加一个job,然后执行,就可以了 5秒整倍数,就执行这个函数 # coding:utf-8 from apscheduler.sche ...

  4. Python 定时任务的实现方式

    本文转载自: https://lz5z.com/Python%E5%AE%9A%E6%97%B6%E4%BB%BB%E5%8A%A1%E7%9A%84%E5%AE%9E%E7%8E%B0%E6%96% ...

  5. ansible定时任务模块和用户组模块使用

    接上篇,还是一些基础模块的使用,这里主要介绍的是系统模块的使用. 下面例子都进行过相关的实践,从而可以直接进行使用相关的命令. 3.用户模块的使用 用户模块主要用来管理用户账号和用户的属性(对远程主机 ...

  6. Python定时任务框架APScheduler

    http://blog.csdn.net/chosen0ne/article/details/7842421 APScheduler是基于Quartz的一个Python定时任务框架,实现了Quartz ...

  7. Python定时任务

    在项目中,我们可能遇到有定时任务的需求.其一:定时执行任务.例如每天早上 8 点定时推送早报.其二:每隔一个时间段就执行任务.比如:每隔一个小时提醒自己起来走动走动,避免长时间坐着.今天,我跟大家分享 ...

  8. [Dynamic Language] Python定时任务框架

    APScheduler是一个Python定时任务框架,使用起来十分方便.提供了基于日期.固定时间间隔以及crontab类型的任务,并且可以持久化任务.并以daemon方式运行应用. 在APSchedu ...

  9. [转]Python定时任务框架APScheduler

    APScheduler是基于Quartz的 一个Python定时任务框架,实现了Quartz的所有功能,使用起来十分方便.提供了基于日期.固定时间间隔以及crontab类型的任务,并且可以 持久化任务 ...

随机推荐

  1. [转] 如何让代码可测试化(C#)

    让代码可测试化 本篇介绍如何把我们目前最常见的代码转换为可以单元测试的代码,针对业务逻辑层来实现可测试性,我们以银行转账为例,通常代码如下: public class TransferControll ...

  2. 1.Java设计模式-工厂模式

    1.简单工厂模式(Factory Method) 常用的工厂模式是静态工厂模式,利用static修饰方法,作为一种类似于常见的工具类Utils等辅助效果,一般情况下工厂类不需要实例化. //1.定义一 ...

  3. 网络安全之——DNS欺骗实验

        ---------------发个帖证明一下存在感,希望各位大牛们,别喷我!!谢谢--------------         DNS(域名系统)的作用是把网络地址(域名,以一个字符串的形式) ...

  4. ThreadPoolExecutor线程池中线程不能超过核心线程数量的问题

    int arg1=2;//核心线程 int arg2=40;//最大线程数量 int arg3=100;//空余保留时间 ThreadPoolExecutor pool=new ThreadPoolE ...

  5. redis集群的远程管理与监控

    一.redis集群的重要性 目前大部分的互联网平台,都会用到Redis内存数据库,以提高响应速度,提升用户使用体验. 为了实现Redis的高可用,通常都会布署Redis集群,使用Redis-Senti ...

  6. Tinymce 编辑器添加自定义图片管理插件

    在使用Tinymce的过程中需要用到图片上传功能,而提供的上传插件在上传文件后是给了一个连接地址,就想用户需要什么图片,不能用最直观的方式表现出来么! 虽然官网上也有一个文件管理的插件moxieman ...

  7. sql: postgreSQL sql script

    SELECT * from pg_class c,pg_attribute a,pg_type t where c.relname='BookKindList' and a.attnum>0 a ...

  8. 浅谈ul布局以及table布局

    我个人对于某些言论说要注重html语义化在布局中的应用,我反而不怎么感冒,试试兼容IE7&&项目期相对较赶的情况下,我还是推荐快速开发为主,兼容性强为主. 如果布局中需要用户边框,推荐 ...

  9. Windows 环境下 NodeJs 开发 Log

    安装 NodeJs, npm. 环境变量配置. 1, Grunt 安装 :  npm install -g grunt-clinpm install -g grunt package.json { & ...

  10. Android中使用异步线程更新UI视图的几种方法

    在Android中子线程是不能更新ui的. 所以我们要通过其他方式来动态改变ui视图, 1.runOnUiThreadactivity提供的一个轻量级更新ui的方法,在Fragment需要使用的时候要 ...