日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python定时任务_Python定时任务工具--APScheduler

發(fā)布時間:2023/12/20 python 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python定时任务_Python定时任务工具--APScheduler 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

APScheduler (advanceded python scheduler)是一款Python開發(fā)的定時任務(wù)工具。

特點:

不依賴于Linux系統(tǒng)的crontab系統(tǒng)定時,獨立運行

可以動態(tài)添加新的定時任務(wù),如下單后30分鐘內(nèi)必須支付,否則取消訂單,就可以借助此工具(每下一單就要添加此訂單的定時任務(wù))

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

1 安裝

pip install apscheduler復(fù)制代碼

2 組成

APScheduler 由以下四部分組成:

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

job stores 存儲器 可以將定時持久存儲

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

schedulers 調(diào)度器 常用的有BackgroundScheduler(后臺運行)和BlockingScheduler(阻塞式)

3 使用方式

from apscheduler.schedulers.background import BlockingScheduler

# 創(chuàng)建定時任務(wù)的調(diào)度器對象

scheduler = BlockingScheduler()

# 創(chuàng)建執(zhí)行器

executors = {

'default': ThreadPoolExecutor(20),

}

# 定義定時任務(wù)

def my_job(param1, param2): # 參數(shù)通過add_job()args傳遞傳遞過來

print(param1) # 100

print(param2) # python

# 向調(diào)度器中添加定時任務(wù)

scheduler.add_job(my_job, 'date', args=[100, 'python'], executors=executors)

# 啟動定時任務(wù)調(diào)度器工作

scheduler.start()復(fù)制代碼

4 調(diào)度器 Scheduler

負(fù)責(zé)管理定時任務(wù)

BlockingScheduler: 作為獨立進程時使用from apscheduler.schedulers.blocking import BlockingScheduler

scheduler = BlockingScheduler()

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

BackgroundScheduler: 在框架程序(如Django、Flask)中使用.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)用的時候可以使用。

4 執(zhí)行器 executors

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

ThreadPoolExecutorfrom apscheduler.executors.pool import ThreadPoolExecutor

ThreadPoolExecutor(max_workers) 復(fù)制代碼

使用方法from apscheduler.executors.pool import ThreadPoolExecutor

executors = {

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

}

scheduler = BackgroundScheduler(executors=executors)復(fù)制代碼

ProcessPoolExecutorfrom apscheduler.executors.pool import ProcessPoolExecutor

ProcessPoolExecutor(max_workers)復(fù)制代碼

使用方法from apscheduler.executors.pool import ProcessPoolExecutor

executors = {

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

}

scheduler = BackgroundScheduler(executors=executors)復(fù)制代碼

5 觸發(fā)器 Trigger

指定定時任務(wù)執(zhí)行的時機。

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

from datetime import date

# 在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')

# 立即執(zhí)行

sched.add_job(my_job, 'date')

sched.start()復(fù)制代碼

2) interval 經(jīng)過指定的時間間隔執(zhí)行

weeks (int) – number of weeks to wait

days (int) – number of days to wait

hours (int) – number of hours to wait

minutes (int) – number of minutes to wait

seconds (int) – number of seconds to wait

start_date (datetime|str) – starting point for the interval calculation

end_date (datetime|str) – latest possible date/time to trigger on

timezone (datetime.tzinfo|str) – time zone to use for the date/time calculations

from datetime import datetime

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

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

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

sched.add_job(job_function, 'interval', hours=2, start_date='2012-10-10 09:30:00', end_date='2014-06-15 11:00:00')復(fù)制代碼

3) cron 按指定的周期執(zhí)行

year (int|str) – 4-digit year

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

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

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

day_of_week (int|str) – number or name of weekday (0-6 or mon,tue,wed,thu,fri,sat,sun)

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

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

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

start_date (datetime|str) – earliest possible date/time to trigger on (inclusive)

end_date (datetime|str) – latest possible date/time to trigger on (inclusive)

timezone (datetime.tzinfo|str) – time zone to use for the date/time calculations (defaults to scheduler timezone)

# 在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')復(fù)制代碼

6.任務(wù)存儲

MemoryJobStore 默認(rèn)內(nèi)存存儲

MongoDBJobStore 任務(wù)保存到MongoDBfrom apscheduler.jobstores.mongodb import MongoDB

JobStoreMongoDBJobStore()復(fù)制代碼

RedisJobStore 任務(wù)保存到redisfrom apscheduler.jobstores.redis import RedisJobStore

RedisJobStore()復(fù)制代碼

7 配置方法

方法1

from apscheduler.schedulers.background import BackgroundScheduler

from apscheduler.executors.pool import ThreadPoolExecutor

executors = {

'default': ThreadPoolExecutor(20),

}

conf = { # redis配置

"host":127.0.0.1,

"port":6379,

"db":15, # 連接15號數(shù)據(jù)庫

"max_connections":10 # redis最大支持300個連接數(shù)

}

scheduler = BackgroundScheduler(executors=executors)

scheduler.add_jobstore(jobstore='redis', **conf) # 添加任務(wù)持久化存儲方式,如果未安裝redis可省略此步驟復(fù)制代碼

方法2

from pytz import utc

from apscheduler.schedulers.background import BackgroundScheduler

from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore

from apscheduler.executors.pool import ProcessPoolExecutor

executors = {

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

'processpool': ProcessPoolExecutor(max_workers=5)

}

scheduler = BackgroundScheduler()

# .. 此處可以編寫其他代碼

# 使用configure方法進行配置

scheduler.configure(executors=executors)復(fù)制代碼

8 啟動

scheduler.start()復(fù)制代碼

對于BlockingScheduler ,程序會阻塞在這,防止退出,作為獨立進程時使用。(可以用來生成靜態(tài)頁面)

對于BackgroundScheduler,可以在應(yīng)用程序中使用。不再以單獨的進程使用。(如30分鐘內(nèi)取消訂單)

9 擴展

任務(wù)管理

方式1

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

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

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

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

方式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ù)復(fù)制代碼

調(diào)整任務(wù)調(diào)度周期

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

scheduler.reschedule_job('my_job_id', trigger='cron', minute='*/5')復(fù)制代碼

停止APScheduler運行

scheduler.shutdown()復(fù)制代碼

10 綜合使用

這里提供30分鐘取消訂單支付的思路,可以使用Flask或者Django程序都能實現(xiàn),這里是在django應(yīng)用中動態(tài)的添加一個定時任務(wù),調(diào)度器需要使用BackgroundScheduler。下面先定義執(zhí)行訂單取消的任務(wù)。

from apscheduler.executors.pool import ThreadPoolExecutor

from datetime import datetime, timedelta

from apscheduler.schedulers.blocking import BackgroundScheduler

from goods.models import SKU

from orders.models import OrderGoods

def cancel_order_job(order_id, sku_id, stock, sales):

# 將訂單商品和訂單信息篩選出來

order_goods = OrderGoods.objects.filter( order_id=order_id, sku_id=sku_id)

order_goods.delete() # 刪除訂單

try:

sku = SKU.objects.get(id=sku_id)

sku.stock += stock # 訂單刪掉后商品表里的庫存恢復(fù)

sku.sales -= sales # 商品表里銷量還原

sku.save()

except Exception as e:

print(e)

復(fù)制代碼

具體操作哪些表要根據(jù)自身表的設(shè)計來定,大致是上面的思路。然后在生成訂單的視圖中同時生成取消訂單的任務(wù)。然后將取消訂單cancel_order_job()需要的參數(shù)傳遞過去,注意要判定當(dāng)前訂單的狀態(tài)為未支付狀態(tài)。

from datetime import datetime, timedelta

class OrderCommitView(View):

def post(self, request):

# ... 此處省略生成訂單相關(guān)邏輯

if status == OrderInfo.STATUS.UNPADED: # 待支付狀態(tài)

executors = {

'default': ThreadPoolExecutor(10)

}

now = datetime.now()

delay = now + timedelta(minutes=30) # 從當(dāng)前下訂單延時30分鐘后

scheduler = BackgroundScheduler(executors=executors)

# 添加定時任務(wù)

scheduler.add_job(cancel_order_job, 'date', run_date=delay,

args=[order_id, sku.id, sku.stock, sku.sales])

scheduler.start()

# ....省略其他業(yè)務(wù)及返回

復(fù)制代碼

注意:如果需要周期性的執(zhí)行一個定時任務(wù),如果用到了django中模型類或者Flask的配置信息等相關(guān)信息,需要將框架的配置信息導(dǎo)入。如果是Flask中,還要導(dǎo)入上下文環(huán)境。

總結(jié)

以上是生活随笔為你收集整理的python定时任务_Python定时任务工具--APScheduler的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。