Jobs scheduling
If you have tasks that need to be performed periodically, you could setup crontab-like jobs with the
builtin app.Cron()
(it returns an app scoped
cron.Cron
value)
.
The jobs scheduler is started automatically on app serve
, so all you have to do is register a
handler with
app.Cron().Add(name, cronExpr, handler)
or
app.Cron().MustAdd(name, cronExpr, handler)
(the latter panic if the cron expression is not valid).
Each scheduled job runs in its own goroutine and must have:
- name - identifier for the scheduled job; could be used to replace or remove an existing job
- cron expression like
0 0 * * *
( supports numeric list, steps, ranges or macros ) - handler - the function that will be executed everytime when the job runs
To remove already registered cron job you can call
app.Cron().Remove(name)
Here is one minimal example:
// main.go
package main
import (
"log"
"github.com/pocketbase/pocketbase"
)
func main() {
app := pocketbase.New()
// prints "Hello!" every 2 minutes
app.Cron().MustAdd("hello", "*/2 * * * *", func() {
log.Println("Hello!")
})
if err := app.Start(); err != nil {
log.Fatal(err)
}
}