在前篇為自動更新內容,
所以加了排程內容,
這篇加寫內容介紹Tasks。
前篇code
from discord.ext import tasks
def _init(Bot):
@tasks.loop(minutes=1)
async def running():
print("run")
running.start()
可控制排程的時間
| 名稱 | 資料型態 | 說明 |
|---|---|---|
| seconds | float | 秒數一次 |
| minutes | float | 分鐘一次 |
| hours | float | 小時一次 |
| time | datetime.time | 確切時間 |
| current_loop | int | 循環的次數 |
| next_iteration | datetime.datetime | 循環的下一次時間 |
Method還有很多,可以在上方 @tasks.loop 內容查看,
其中下面內容可以增加使用的工具。
裝飾方法|說明
@before_loop|排程開始運行之前調用的方法
@after_loop|排程結束後呼叫方法
@error|排程遇到未處理的異常呼叫
example:
count = 0
# 循環五次,每10分鐘執行
@tasks.loop(minutes=10, count=5)
async test():
count = count + 1
# 方法執行前執行的動作
@test.before_loop
async def after_count():
print("開始!")
# 方法執行完後要執行的動作
@test.after_loop
async def before_count():
print(f"count:{count}")
| 方法 | 說明 |
|---|---|
| start | 啟動排程 |
| stop | 排程停止(但仍會執行@after_loop) |
| cancel | 排程取消 |
| restart | 重新啟動 |
| get_task | 取得內部任務或正在運行的任務 |
| is_being_cancelled | 任務是否正在取消 |
| failed | 內部任務是否失敗 |
| is_running | 檢查任務目前是否正在運行 |
| change_interval | 變更等待時間間隔 |
| 異常方法 | 說明 |
|---|---|
| add_exception_type | 新增要在重新連接邏輯期間處理的異常類型 |
| clear_exception_types | 刪除所有已處理的異常類型 |
| remove_exception_type | 刪除重新連接邏輯期間處理的異常類型 |