KScript 文档
ZH

队列与作业:KScript.Queue

创建作业

编写作业

kscript make job SendWelcome 会为你生成一个作业文件。作业名称以大写字母开头。其字段的写法与 类型 相同:name: type,可省略的字段写作 name?: type,以及 name: type = default。

在 handle 内部,每个字段都是一个变量,$this 即为该作业。在编辑器中,未包含 fn handle() 的作业会提供一个快速修复来生成它。

排队的作业会以 JSON 形式保存,直到工作进程运行它,因此请保持其字段小巧且简单。传入用户的 id,而不是用户对象。出于同样的原因,password 字段会导致错误。

了解当前是第几次尝试

$job 会告知当前正在运行的是第几次尝试,这在作业于重试时行为不同的情况下很有用:

<import package="KScript.Queue" />

<job name="SyncContacts" tries="3">
  <field name="account_id" type="int" />

  <fn name="handle">
    <echo>Attempt {$job.attempt} of {$job.tries} for account {.account_id}</echo>
  </fn>
</job>
import KScript.Queue

job SyncContacts(tries: 3) {
  account_id: int

  fn handle() {
    echo "Attempt {$job.attempt} of {$job.tries} for account {.account_id}"
  }
}

$job 包含排队作业的 id(以 null 运行时为 ->run())、其 name、attempt(首次运行时为 1)、可获得的 tries 次数、其所来自的 queue 和 connection,以及其分发时间(dispatched_at)。

处理失败的作业

添加 fn failed(err) 以便在作业最终失败时执行某些操作。它在最后一次尝试之后运行一次,并携带一个 JobFailed 错误,其 cause 即为最后一次尝试抛出的错误。作业上的灯泡图标会为你自动添加它:

<import package="KScript.Queue" />

<job name="SendInvoice" tries="3">
  <field name="invoice_id" type="int" />

  <fn name="handle">
    <echo>Sending invoice {.invoice_id}</echo>
  </fn>

  <fn name="failed" params="err">
    <echo>Gave up on invoice {.invoice_id}: {$err.message}</echo>
  </fn>
</job>
import KScript.Queue

job SendInvoice(tries: 3) {
  invoice_id: int

  fn handle() {
    echo "Sending invoice {.invoice_id}"
  }

  fn failed(err) {
    echo "Gave up on invoice {.invoice_id}: {$err.message}"
  }
}

作业只有这两个函数。请将辅助函数放在作业之外。

Edit this page on GitHub