소개
일부 작업은 사람이 기다리게 하면 안 됩니다. 이메일 보내기, 사진 크기 조정, 느린 API 호출 등입니다. KScript.Queue를 쓰면 그런 작업을 나중에 실행되는 작업으로 넘길 수 있습니다. ->dispatch()은 작업을 큐에 넣고 즉시 돌아옵니다. kscript worker는 큐에서 작업을 꺼내 실행합니다. 실패한 작업은 다시 시도하고, 계속 실패하는 작업은 이유를 확인할 수 있도록 보관합니다.
작업은 job, 그 필드, 그리고 작업을 수행하는 handle 함수로 선언합니다:
<import package="KScript.Queue" />
<job name="SendWelcome" queue="mail" tries="5" description="Sends the welcome email to a new user.">
<field name="user_id" type="int" />
<field name="email" type="email" />
<fn name="handle">
<echo>Sending the welcome email to {.email}</echo>
</fn>
</job>import KScript.Queue
/// Sends the welcome email to a new user.
job SendWelcome(queue: 'mail', tries: 5) {
user_id: int
email: email
fn handle() {
echo "Sending the welcome email to {.email}"
}
}jobs/send-welcome.kscript로 저장하고, 프로젝트 어디에서든 디스패치하세요:
<import package="KScript.Queue" />
<import path="jobs/send-welcome.kscript" />
<do>SendWelcome(user_id: 7, email: 'joan@example.com')->dispatch()</do>import KScript.Queue
import "jobs/send-welcome.kscript"
SendWelcome(user_id: 7, email: 'joan@example.com')->dispatch()그리고 다른 터미널에서 워커를 시작하세요:
| 명령어 | 기능 |
|---|---|
kscript worker | 들어오는 작업을 Ctrl+C로 멈출 때까지 실행합니다. |
작업을 선언하거나 디스패치하는 모든 파일은 import KScript.Queue로 시작합니다. 없으면 kscript check가 job is part of KScript.Queue. Add import KScript.Queue라고 알려주며, 편집기가 추가를 제안합니다.