KScript 文档
ZH

队列与作业:KScript.Queue

简介

有些工作不应该让用户等待:发送邮件、缩放图片、调用缓慢的 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()

然后在另一个终端中启动一个 worker:

命令作用
kscript worker持续运行任务,直到按下 Ctrl+C 为止。

声明或分派任务的每个文件都以 import KScript.Queue 开头。如果没有它,kscript check 会提示 job is part of KScript.Queue. Add import KScript.Queue,并且编辑器会提议添加它。