久久久精品一区ed2k-女人被男人叉到高潮的视频-中文字幕乱码一区久久麻豆樱花-俄罗斯熟妇真实视频

APScheduler的使用是怎么樣的

今天就跟大家聊聊有關(guān)APScheduler的使用是怎么樣的,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

成都創(chuàng)新互聯(lián)公司是一家專業(yè)提供驛城企業(yè)網(wǎng)站建設(shè),專注與成都網(wǎng)站設(shè)計、成都做網(wǎng)站、HTML5、小程序制作等業(yè)務(wù)。10年已為驛城眾多企業(yè)、政府機構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)站設(shè)計公司優(yōu)惠進行中。

1.簡介

APScheduler 是一款Python開發(fā)的定時任務(wù)工具, 跨平臺運行, 不依賴Linux系統(tǒng)的crontab服務(wù), 在windows上也可以運行

官方文檔的地址是 https://apscheduler.readthedocs.io/en/latest/index.html

簡單介紹

APScheduler具有四種組件

觸發(fā)器(triggers) 指定定時任務(wù)的執(zhí)行的時機

存儲器(job stores) 可以定時持久化存儲, 可以保存在數(shù)據(jù)庫中或redis

# 存儲在redis中

from apscheduler.jobstores.redis import RedisJobStore

# 存儲在mongo中

from apscheduler.jobstores.MongoDB import MongoDBJobStore

# 存儲在數(shù)據(jù)庫中

from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore

執(zhí)行器(executors) 在定時任務(wù)執(zhí)行時, 進程或者線程的方式執(zhí)行任務(wù)

調(diào)度器(schedulers)

# 以后臺的方式運行

from apscheduler.schedulers.background import BackgroundScheduler

# 以阻塞的方式運行, 前臺運行

from apscheduler.schedulers.background import BlockingScheduler

對添加的任務(wù)可以做持久保存

2.安裝

pip install apscheduler

3. 觸發(fā)器 Trigger

date在特定的時間日期執(zhí)行

from datetime import date

from apscheduler.schedulers.blocking import BlockingScheduler

sched = BlockingScheduler()

def my_job(text):

print(text)

# 在2019年11月6日00:00:00執(zhí)行

sched.add_job(my_job, 'date', run_date=date(2019, 11, 6))

# 在2019年11月6日16:30:05, 可以指定運行的詳細時間

sched.add_job(my_job, 'date', run_date=datetime(2009, 11, 6, 16, 30, 5))

# 運行時間也可以是字符串的形式

sched.add_job(my_job, 'date', run_date='2009-11-06 16:30:05', args=['text])

# 立即執(zhí)行

sched.add_job(my_job, 'date')

sched.start()

interval:以固定的時間間隔運行作業(yè)時使用

weeks (int) – 間隔的周數(shù)

days (int) – 間隔的天數(shù)

hours (int) – 間隔的小時

minutes (int) –間隔的分鐘

seconds (int) – 間隔的秒

start_date (datetime|str) – 間隔時間的起點

end_date (datetime|str) – 間隔時間的結(jié)束點

timezone (datetime.tzinfo|str) – 時區(qū)

jitter (int|None) – 將作業(yè)執(zhí)行 延遲的時間

from datetime import datetime

# 每兩小時執(zhí)行一次

sched.add_job(job_function, 'interval', hours=2)

# 在2018年10月10日09:30:00 到2019年6月15日11:00:00的時間內(nèi),每兩小時執(zhí)行一次

sched.add_job(job_function, 'interval', hours=2, start_date='2018-10-10 09:30:00', end_date='2019-06-15 11:00:00')

cron:在一天中的特定時間定期運行作業(yè)時使用

常見的參數(shù)

year (int|str) – 4位數(shù)的年份

month (int|str) – month (1-12)

day (int|str) – day (1-31)

week (int|str) – ISO week (1-53)

day_of_week (int|str) –工作日的編號或名稱(0-6或周一,周二,周三,周四,周五,周六,周日)

hour (int|str) – 小時(0-23)

minute (int|str) – 分鐘 (0-59)

second (int|str) – 秒 (0-59)

start_date (datetime|str) –最早觸發(fā)的日期/時間(包括)

end_date (datetime|str) – 結(jié)束觸發(fā)的日期/時間(包括)

timezone (datetime.tzinfo|str) – 時區(qū)

jitter (int|None) – 將執(zhí)行作業(yè)延遲幾秒執(zhí)行

常見的表達式類型

# 在6、7、8、11、12月的第三個周五的00:00, 01:00, 02:00和03:00 執(zhí)行

sched.add_job(job_function, 'cron', month='6-8,11-12', day='3rd fri', hour='0-3')

# 在2014年5月30日前的周一到周五的5:30執(zhí)行

sched.add_job(job_function, 'cron', day_of_week='mon-fri', hour=5, minute=30, end_date='2014-05-30')

# 執(zhí)行的方式 用裝飾器的形式, 每個月的最后一個星期日執(zhí)行

@sched.scheduled_job('cron', id='my_job_id', day='last sun')

def some_decorated_task():

print("I am printed at 00:00:00 on the last Sunday of every month!")

# 可以使用標準的crontab表達式執(zhí)行

sched.add_job(job_function, CronTrigger.from_crontab('0 0 1-15 may-aug *'))

# 延遲120秒執(zhí)行

sched.add_job(job_function, 'cron', hour='*', jitter=120)

calendarinterval:在一天的特定時間以日歷為基礎(chǔ)的間隔運行作業(yè)時使用

參數(shù)和 interval 中的參數(shù)設(shè)置相同

from datetime import datetime

from apscheduler.schedulers.blocking import BlockingScheduler

def job_function():

print("Hello World")

sched = BlockingScheduler()

# 每個月的15:36:00 執(zhí)行這個任務(wù)

sched.add_job(job_function, 'calendarinterval', months=1, hour=15, minute=36)

# 從今天開始 每兩個月的 15點36分執(zhí)行, 時間范圍是 2019-6-16到 2020-3-26

sched.add_job(job_function, 'calendarinterval', months=2, start_date='2019-06-16',

end_date='2020-03-16', hour=15, minute=36)

sched.start()

4. 儲存器

REDIS_CONF = {

"password": "xxxxx",

"host": "192.168.137.120",

"port": 6379,

"db": 0}

from apscheduler.jobstores.redis import RedisJobStore

from apscheduler.jobstores.mongodb import MongoDBJobStore

from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore

# 存儲器

job_stores = {

# 使用redis存儲

'redis': RedisJobStore(jobs_key=jobs_key, run_times_key=run_times_key, **REDIS_CONF),

# 使用mongo存儲

'mongo': MongoDBJobStore(),

# 數(shù)據(jù)庫存儲

'default': SQLAlchemyJobStore(url='sqlite:///jobs.sqlite')

}

# 執(zhí)行器

executors = {

'default': ThreadPoolExecutor(20), # 20個線程

'processpool': ProcessPoolExecutor(5) # 5個進程

}

job_defaults = {

'coalesce': False, # 相同任務(wù)觸發(fā)多次

'max_instances': 3 # 每個任務(wù)最多同時觸發(fā)三次

}

# 使用配置, 啟動

scheduler = BackgroundScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults, timezone=utc)

5. 執(zhí)行器 在定時任務(wù)該執(zhí)行時,以進程或線程方式執(zhí)行任務(wù)

# 線程的方式執(zhí)行

from apscheduler.executors.pool import ThreadPoolExecutor

executors = {

'default': ThreadPoolExecutor(20) # 最多20個線程同時執(zhí)行

}

scheduler = BackgroundScheduler(executors=executors)

# 進程的方式

executors = {

'default': ProcessPoolExecutor(5) # 最多5個進程同時執(zhí)行

}

6.調(diào)度器

BlockingScheduler: 作為獨立進程時使用

from apscheduler.schedulers.blocking import BlockingScheduler

scheduler = BlockingScheduler()

scheduler.start()

# 此處程序會發(fā)生阻塞復(fù)制代碼

BackgroundScheduler 后臺運行, 在框架中使用

from apscheduler.schedulers.background import BackgroundScheduler

scheduler = BackgroundScheduler()

scheduler.start()

# 此處程序不會發(fā)生阻塞復(fù)制代碼

AsyncIOScheduler : 當(dāng)你的程序使用了asyncio的時候使用。

GeventScheduler : 當(dāng)你的程序使用了gevent的時候使用。

TornadoScheduler : 當(dāng)你的程序基于Tornado的時候使用。

TwistedScheduler : 當(dāng)你的程序使用了Twisted的時候使用

QtScheduler : 如果你的應(yīng)用是一個Qt應(yīng)用的時候可以使用。

7. 配置的三中方法

方法1

from pytz import utc

from apscheduler.schedulers.background import BackgroundScheduler

from apscheduler.jobstores.mongodb import MongoDBJobStore

from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore

from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor

jobstores = {

'mongo': MongoDBJobStore(),

'default': SQLAlchemyJobStore(url='sqlite:///jobs.sqlite')

}

executors = {

'default': ThreadPoolExecutor(20), # 最大線程數(shù)

'processpool': ProcessPoolExecutor(5) # 最大進程數(shù)

}

job_defaults = {

'coalesce': False,

'max_instances': 3 # 同一個任務(wù)啟動實例的最大個數(shù)

}

# 配置的使用方式

scheduler = BackgroundScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults, timezone=utc)鄭州婦科檢查哪家好 http://www.zzkdfk.com/

方法2

from apscheduler.schedulers.background import BackgroundScheduler

# 使用字典的形式添加配置

scheduler = BackgroundScheduler({

'apscheduler.jobstores.mongo': {

'type': 'mongodb'

},

'apscheduler.jobstores.default': {

'type': 'sqlalchemy',

'url': 'sqlite:///jobs.sqlite'

},

'apscheduler.executors.default': {

'class': 'apscheduler.executors.pool:ThreadPoolExecutor',

'max_workers': '20'

},

'apscheduler.executors.processpool': {

'type': 'processpool',

'max_workers': '5'

},

'apscheduler.job_defaults.coalesce': 'false',

'apscheduler.job_defaults.max_instances': '3',

'apscheduler.timezone': 'UTC',

})

方法3

from pytz import utc

from apscheduler.schedulers.background import BackgroundScheduler

from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore

from apscheduler.executors.pool import ProcessPoolExecutor

jobstores = {

'mongo': {'type': 'mongodb'},

'default': SQLAlchemyJobStore(url='sqlite:///jobs.sqlite')

}

executors = {

'default': {'type': 'threadpool', 'max_workers': 20},

'processpool': ProcessPoolExecutor(max_workers=5)

}

job_defaults = {

'coalesce': False,

'max_instances': 3

}

scheduler = BackgroundScheduler()

# 使用調(diào)度器對象的 configure屬性增加 存儲器, 執(zhí)行器 存儲器 的配置

scheduler.configure(jobstores=jobstores, executors=executors, job_defaults=job_defaults, timezone=utc)

8. 定時任務(wù)啟動

scheduler.start()

對于BlockingScheduler ,程序會阻塞在這,防止退出,作為獨立進程時使用。

對于BackgroundScheduler,可以在應(yīng)用程序中使用。不再以單獨的進程使用。

9. 任務(wù)管理

方式1

job = scheduler.add_job(myfunc, 'interval', minutes=2) # 添加任務(wù)

job.remove() # 刪除任務(wù)

job.pause() # 暫定任務(wù)

job.resume() # 恢復(fù)任務(wù)

job.shutdown() # 關(guān)閉調(diào)度

job.shutdown(wait=False) # 不等待正在運行的任務(wù)

方式2

scheduler.add_job(myfunc, 'interval', minutes=2, id='my_job_id') # 添加任務(wù)

scheduler.remove_job('my_job_id') # 刪除任務(wù)

scheduler.pause_job('my_job_id') # 暫定任務(wù)

scheduler.resume_job('my_job_id') # 恢復(fù)任務(wù)

修改調(diào)度, 修改調(diào)度的配置屬性

job.modify(max_instances=6, name='Alternate name')

# 更改觸發(fā)器

scheduler.reschedule_job('my_job_id', trigger='cron', minute='*/5')

獲取作業(yè)列表 get_jobs() 方法, 返回的是Job實例列表

10.日志的使用

項目中沒有使用日志記錄,

import logging

logging.basicConfig()

logging.getLogger('apscheduler').setLevel(logging.DEBUG)

集成到項目中的日志中

logger = logging.getLogger("django")

......

scheduler = BackgroundScheduler(jobstores=job_stores, executors=executors, job_defaults=job_defaults)

scheduler._logger = logger

11.完整的例子

REDIS_CONF = {

"password": "xxxxx",

"host": "192.168.137.120",

"port": 6379,

"db": 0}

logger = logging.getLogger("django")

jobs_key = 'collection_api_apscheduler.jobs'

run_times_key = 'collection_api_apscheduler.run_times'

job_stores = {

'default': RedisJobStore(jobs_key=jobs_key, run_times_key=run_times_key, **REDIS_CONF)

}

executors = {

'default': {'type': 'threadpool', 'max_workers': 60}

}

job_defaults = {

'coalesce': True, # 相同任務(wù)同時觸發(fā)多次時,只運行一次

'max_instances': 3,

'misfire_grace_time': 30, # 過期30秒依然執(zhí)行該任務(wù)

}

scheduler = BackgroundScheduler(jobstores=job_stores, executors=executors, job_defaults=job_defaults)

scheduler._logger = logger

# 如果持久化的調(diào)度器中作業(yè)列表, 調(diào)度器繼續(xù)執(zhí)行

if scheduler.get_jobs():

scheduler.resume()

# 添加定時任務(wù)

scheduler.add_job(handle_news_task, 'date', id='handle_news_task', replace_existing=True)

scheduler.add_job(......)

scheduler.start()

看完上述內(nèi)容,你們對APScheduler的使用是怎么樣的有進一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。

文章標題:APScheduler的使用是怎么樣的
本文網(wǎng)址:http://sd-ha.com/article32/ggepsc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供面包屑導(dǎo)航響應(yīng)式網(wǎng)站、網(wǎng)站設(shè)計公司網(wǎng)頁設(shè)計公司、營銷型網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

綿陽服務(wù)器托管