KScript docs
EN

Queues and jobs: KScript.Queue

Introduction

Some work shouldn't make a person wait: sending an email, resizing a picture, calling a slow API. KScript.Queue lets you hand that work off as a job to run later. ->dispatch() puts a job on a queue and returns at once. kscript worker takes jobs off the queue and runs them. It tries a failed job again, and keeps jobs that keep failing so you can see why.

A job is declared with job, its fields and a handle function that does the work:

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

Save it as jobs/send-welcome.kscript, and dispatch it from anywhere in the project:

<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()

Then start a worker in another terminal:

CommandWhat it does
kscript workerRuns jobs as they arrive, until Ctrl+C.

Every file that declares or dispatches a job starts with import KScript.Queue. Without it, kscript check says job is part of KScript.Queue. Add import KScript.Queue, and the editor offers to add it.