Zkzcfg8520
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
Publish Note

Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

Your note will be visible on your profile and discoverable by anyone.
Your note is now live.
This note is visible on your profile and discoverable online.
Everyone on the web can find and read all notes of this public team.
See published notes
Unpublish note
Please check the box to agree to the Community Guidelines.
View profile
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
Celery === 介紹 --- Celery 是 Python 的一種套件,此套件的功能可以非同步(asynchronous)執行任務(tasks) / 工作(jobs) ,這種非同步的作法很常見於 Web Application。舉個例子說明適合使用 Celery 的情況也許會更清楚,假設有一使用者需要透過 Web Application 匯出一份龐大的資料(可能執行時間很長,超過 30 分鐘),在這情況之下,我們也無法要求使用者一直開著該網頁不關,這時候比較好的作法就是利用非同步的方式執行匯出資料的工作,把工作移到背景執行,然後告知使用者工作執行完畢後會透過 Email / 即時通訊軟體通知工作完成,讓使用者可以回來下載資料,如此一來,使用者就不需要一直開著網頁佔用伺服器的連線數,Celery 就是應用在這種非同步執行的情況下。 ![image](https://hackmd.io/_uploads/HyEBMlPcC.png) 架構流程圖 --- ![image](https://hackmd.io/_uploads/HJDMmYU5R.png) Celery Application --- 在使用 Celery 時,需要實例化(instantiated) Celery ,這個實例(instance)就被稱為 Application 或者 `app` ,因此可以看到 Celery 文件中通常會用 `app` 來命名。另外,Celery 是 thread-safe 的,所以可以多個 Celery Application 共存。 程式碼 ```=== from celery import Celery app = Celery() ``` Task --- Task 是 Celery 執行的最小單位,如果要讓工作可以非同步進行,就得把這些工作切分成一個個 Task 。等於是定義好 Celery Application 提供哪些 Task 被非同步執行。 ### 異步任務 (Asynchronous Task) 異步任務是指那些不會阻塞當前程序或者進程的執行的任務。這些任務在背景中運行,允許主程序繼續處理其他事務,而不需要等待異步任務完成。 特點: - 非阻塞: 主程序發起任務後可以繼續執行,不需等待異步任務完成。 - 背景處理: 任務在背景進行,通常不影響主程序的響應時間。 - 應用場景: 處理需時間的請求、性能密集型或I/O密集型任務等。 ### 定時任務 (Scheduled Task) 定時任務指的是那些被設定在特定時間或按照一定時間間隔重複執行的任務。這種任務通常用於需要定期執行的操作,比如數據備份、報告生成、定期檢查系統狀態等。 特點: - 時間控制: 任務根據預設的時間表自動觸發。 - 周期性: 任務可以設定為一次性的或重複執行(如每日、每週等)。 - 應用場景: 數據備份、自動報告、定期維護作業等。 以下為官方文件中的範例 Task : ```=== @app.task def add(x, y): return x + y ``` Worker --- 有 Task 之後,就需要有 Process(排程) 負責執行 Task ,這樣才能夠達到非同步執行的目標,這時候就需要 Worker 在背景執行 Task 。所以 Celery 官方文件也提到了啟動 Worker 的指令: ```=== #終端機 celery -A task worker --loglevel=info ``` Task Message & Broker --- 定義好 Task 與啟動 Worker 之後,要怎麼叫 Worker 執行 Task 呢 這時候就需要靠 Task Message 告訴 Celery Application 要非同步執行某個 Task , Celery Application 會幫忙找到 Worker 執行 Task 。而 Task Message 本身不會夾帶任何程式碼,只會帶有要執行的 Task 名稱及參數等資訊(如果可以夾帶程式碼就可以執行任意程式碼,造成可怕的安全漏洞)。然而, Celery 並不負責 Task Message 的傳遞,這時候就需要 1 個稱為 Broker 的角色負責傳遞 Task Message ,也因此可以看到 Celery 官方文件提到需要 Broker 。 目前 Celery 支援的 Brokers: RabbitMQ Redis Amazon SQS Zookeeper Result Backend --- 如果要追蹤 Task 的執行的狀態(例如 PENDING, STARTED, SUCCESS, FAILURE, RETRY, REVOKED 等狀態,詳見 Built-in States ),就需要 Result Backend 儲存 Task 的狀態,這就是 Result Backend 的作用,所以也可以看到 Celery 文件中提到 Result Backend 的相關設定。 前置動作 --- - 先把 Broker 安裝好, 這邊統一使用 redis, 因為 redis 同時也可作為 cache server 使用,可以讓系統架構單純許多,開發速度也會快一些,安裝步驟請參考最下方的 "參考資料" 安裝 --- ``` # 安裝 Celery 套件 pip install celery # 安裝 gevent 套件 pip install gevent ``` 程式碼內容 --- ```=== // task.py from celery import Celery app = Celery( 'task', broker='redis://127.0.0.1:6379', // 我們的 broker backend='redis://127.0.0.1:6379/1', // ) //Task 內容 @app.task def add(x, y): return x + y if __name__ == '__main__': app.worker_main() ``` 執行 --- 先啟動 Celery ``` # 執行 Celery Worker celery -A task worker --loglevel=info ``` 創建另一個 py檔, 來使用我們的 Task ```=== // test.py from task import add result = add.delay(4, 6) print(result.get()) ``` 結果 --- ![image](https://hackmd.io/_uploads/SkvaPdPtC.png) Flower 監控工具 --- ![image](https://hackmd.io/_uploads/HyHmsOLcA.png) 安裝 ``` pip install flower ``` 執行指令 ``` celery -A <your_project_name> flower ``` 利用網址進入頁面 ``` http://localhost:5555/ ``` 常用指令 --- | 指令名稱 | 指令功能 | | :--: | :--: | | worker | 啟動 worker | | -A | 指定應用程序名稱 | | -l {DEBUG/INFO/WARNING/ERROR/CRITICAL/FATAL} | 日誌記錄級別 | | -S | 狀態資料庫的路徑,檔名可能會附加 '.db' 擴展名 | | -D | 以背景進程的方式啟動 worker | | -O {default/fair} | 應用優化設定檔 | | --prefetch-multiplier {prefetch multiplier} | 為這個 worker 實例設定自定義的預取倍數值 | | -n {HOSTNAME} | 設定自定義主機名(例如:'w1@%%h'),展開:%%h(主機名),%%n(名稱)和 %%d(域) | | - -purge | 清除隊列(Broker) | 其他指令 ( 輸入指令 celery worker –help ) --- ### Pool Options | 指令用法 | 指令功能 | | :--: | :--: | | -c {concurrency} | 處理隊列的子進程數量 | | -P {prefork/eventlet/gevent/solo/processes/threads/custom} | 池實現 | | -E | 發送與任務相關的事件,這些事件可以被像 celery events、celerymon 等監控捕捉到 | | - -time-limit {FLOAT/INT} | 啟用任務的硬時間限制(以秒為單位的 int/float) | | - -soft-time-limit {FLOAT/INT} | 啟用任務的軟時間限制(以秒為單位的 int/float) | | - -max-tasks-per-child {INT} | 一個池工作進程可以執行的最大任務數,在此之後它將被終止並替換為一個新進程 | | - -max-memory-per-child {INT} | 一個子進程在被替換之前可能消耗的最大常駐內存量(以 KiB 為單位) | ### Queue Options | 指令用法 | 指令功能 | | :--: | :--: | | -Q | 指定隊列列表 | | -X | 排除隊列列表 | | -I | 包含隊列列表 | ### Features Options | 指令用法 | 指令功能 | | :--: | :--: | | - -without-gossip | 不啟用 gossip | | - -without-mingle | 不啟用 mingle | | - -without-heartbeat | 不發送心跳 | | - -heartbeat-interval {INT} | 設定心跳間隔(整數) | | - -autoscale {MIN WORKERS}, {MAX WORKERS} | 自動縮放工作進程數量,從最小到最大 | ### Embedded Beat Options | 指令用法 | 指令功能 | | :--: | :--: | | -B | 啟動嵌入式的 beat | | -s | 設定時程表的檔案名 | | - -scheduler {TEXT} | 指定時程表的調度器 | ### Daemonization Options | 指令用法 | 指令功能 | | :--: | :--: | | -f | 日誌文件的儲存位置;預設為標準錯誤 | | - -pidfile {TEXT} | PID 文件的路徑;預設不使用 PID 文件 | | - -uid {TEXT} | 降低權限至指定的用戶 ID | | - -gid {TEXT} | 降低權限至指定的群組 ID | | - -umask {TEXT} | 以此 umask 創建檔案和目錄 | | - -executable {TEXT} | 覆蓋 Python 可執行檔的路徑 | 實例化 --- 在電腦系統中,任何時候基於某種模型的一個新的東西被建立後,都可以說該模型已經被實例化。這個實例通常與其他基於同一模型的實例有一個共同的資料結構,但儲存在實例中的值是獨立的。這樣,改變一個實例中的值就不會干擾到其他一些實例的值。 在物件導向程式設計中,實例是任何對象的具體實現,建立一個實例被稱為實例化。在類別為基編程中,一個對象就是一個類別的實例,對象由建構函式建立,並由解構函式銷毀。該對象可以稱為類別實例或類對象。並非所有的類都可以被實例化,抽象類就不能被實例化。 參考資料 --- [Broker redis 安裝](https://officeguide.cc/ubuntu-linux-redis-database-installation-configuration-tutorial-examples/) (幫我做到測試資料庫的部分就好) [Celery](https://officeguide.cc/celery-distributed-task-queue-getting-started-1/) [Celery2]( https://zoejoyuliao.medium.com/django-celery-redis-gmail-%E5%AF%84%E4%BF%A1-375904d4224c) [Celery3](https://ithelp.ithome.com.tw/m/articles/10273022) [Celery4](https://hackmd.io/@aaronlife/python-topic-scheduler) [Celery5](https://geeeez.github.io/posts/Celery-timing/)

Import from clipboard

Paste your markdown or webpage here...

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.
Upgrade
All
  • All
  • Team
No template.

Create a template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

Slide Example

API Docs

Edit in VSCode

Install browser extension

Contacts

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Get Full History Access

  • Edit version name
  • Delete

revision author avatar     named on  

More Less

Note content is identical to the latest version.
Compare
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully