KScript docs
EN

Queues and jobs: KScript.Queue

Creating jobs

Writing a job

kscript make job SendWelcome writes a job file for you. A job's name starts with a capital letter. Its fields are written as in a type: name: type, name?: type for one that may be left out, and name: type = default.

Inside handle, each field is a variable and $this is the job. In the editor, a job without fn handle() has a quick fix that writes it.

A queued job is saved as JSON until a worker runs it, so keep its fields small and plain. Pass the user's id, not the user. A password field is an error for the same reason.

Knowing which attempt this is

$job says which attempt is running, which helps when a job behaves differently on a retry:

<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 has the queued job's id (null when it runs with ->run()), its name, the attempt (1 the first time), how many tries it gets, the queue and connection it came from, and when it was dispatched (dispatched_at).

Handling a job that fails

Add fn failed(err) to do something when a job has failed for good. It runs once, after the last try, with a JobFailed error whose cause is the error the last try threw. The lightbulb on a job adds it for you:

<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}"
  }
}

A job has only these two functions. Put helpers outside the job.