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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

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

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

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

特點:

不依賴于Linux系統的crontab系統定時,獨立運行

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

對添加的定時任務可以做持久保存

1 安裝

pip install apscheduler復制代碼

2 組成

APScheduler 由以下四部分組成:

triggers 觸發器 指定定時任務執行的時機

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

executors 執行器 在定時任務該執行時,以進程或線程方式執行任務

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

3 使用方式

from apscheduler.schedulers.background import BlockingScheduler

# 創建定時任務的調度器對象

scheduler = BlockingScheduler()

# 創建執行器

executors = {

'default': ThreadPoolExecutor(20),

}

# 定義定時任務

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

print(param1) # 100

print(param2) # python

# 向調度器中添加定時任務

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

# 啟動定時任務調度器工作

scheduler.start()復制代碼

4 調度器 Scheduler

負責管理定時任務

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

scheduler = BlockingScheduler()

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

BackgroundScheduler: 在框架程序(如Django、Flask)中使用.from apscheduler.schedulers.background import BackgroundScheduler

scheduler = BackgroundScheduler()

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

AsyncIOScheduler : 當你的程序使用了asyncio的時候使用。

GeventScheduler : 當你的程序使用了gevent的時候使用。

TornadoScheduler : 當你的程序基于Tornado的時候使用。

TwistedScheduler : 當你的程序使用了Twisted的時候使用

QtScheduler : 如果你的應用是一個Qt應用的時候可以使用。

4 執行器 executors

在定時任務該執行時,以進程或線程方式執行任務

ThreadPoolExecutorfrom apscheduler.executors.pool import ThreadPoolExecutor

ThreadPoolExecutor(max_workers) 復制代碼

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

executors = {

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

}

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

ProcessPoolExecutorfrom apscheduler.executors.pool import ProcessPoolExecutor

ProcessPoolExecutor(max_workers)復制代碼

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

executors = {

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

}

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

5 觸發器 Trigger

指定定時任務執行的時機。

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

from datetime import date

# 在2019年11月6日00:00:00執行

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

# 立即執行

sched.add_job(my_job, 'date')

sched.start()復制代碼

2) interval 經過指定的時間間隔執行

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

# 每兩小時執行一次

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

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

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

3) cron 按指定的周期執行

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 執行

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

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

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

6.任務存儲

MemoryJobStore 默認內存存儲

MongoDBJobStore 任務保存到MongoDBfrom apscheduler.jobstores.mongodb import MongoDB

JobStoreMongoDBJobStore()復制代碼

RedisJobStore 任務保存到redisfrom apscheduler.jobstores.redis import RedisJobStore

RedisJobStore()復制代碼

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號數據庫

"max_connections":10 # redis最大支持300個連接數

}

scheduler = BackgroundScheduler(executors=executors)

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

方法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)復制代碼

8 啟動

scheduler.start()復制代碼

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

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

9 擴展

任務管理

方式1

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

job.remove() # 刪除任務

job.pause() # 暫定任務

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

方式2

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

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

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

scheduler.resume_job('my_job_id') # 恢復任務復制代碼

調整任務調度周期

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

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

停止APScheduler運行

scheduler.shutdown()復制代碼

10 綜合使用

這里提供30分鐘取消訂單支付的思路,可以使用Flask或者Django程序都能實現,這里是在django應用中動態的添加一個定時任務,調度器需要使用BackgroundScheduler。下面先定義執行訂單取消的任務。

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 # 訂單刪掉后商品表里的庫存恢復

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

sku.save()

except Exception as e:

print(e)

復制代碼

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

from datetime import datetime, timedelta

class OrderCommitView(View):

def post(self, request):

# ... 此處省略生成訂單相關邏輯

if status == OrderInfo.STATUS.UNPADED: # 待支付狀態

executors = {

'default': ThreadPoolExecutor(10)

}

now = datetime.now()

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

scheduler = BackgroundScheduler(executors=executors)

# 添加定時任務

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

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

scheduler.start()

# ....省略其他業務及返回

復制代碼

注意:如果需要周期性的執行一個定時任務,如果用到了django中模型類或者Flask的配置信息等相關信息,需要將框架的配置信息導入。如果是Flask中,還要導入上下文環境。

總結

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

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。