encore-go-cron
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseEncore Go Cron Jobs
Encore Go Cron Jobs
Instructions
使用说明
A declaration in Encore Go ties a schedule to an existing endpoint. The endpoint runs at the chosen cadence. Declare the job as a package-level variable — not inside a function.
cron.NewJob//encore:apigo
package cleanup
import (
"context"
"encore.dev/cron"
)
// 1. The endpoint to call (typically private: //encore:api private)
//encore:api private
func CleanupExpiredSessions(ctx context.Context) error {
// Cleanup logic
return nil
}
// 2. Package-level cron declaration
var _ = cron.NewJob("cleanup-sessions", cron.JobConfig{
Title: "Clean up expired sessions",
Schedule: "0 * * * *", // Every hour
Endpoint: CleanupExpiredSessions,
})在Encore Go中,声明会将调度计划与现有的端点绑定。该端点会按照选定的频率运行。请将任务声明为包级变量——不要在函数内部声明。
cron.NewJob//encore:apigo
package cleanup
import (
"context"
"encore.dev/cron"
)
// 1. 要调用的端点(通常为私有://encore:api private)
//encore:api private
func CleanupExpiredSessions(ctx context.Context) error {
// 清理逻辑
return nil
}
// 2. 包级cron声明
var _ = cron.NewJob("cleanup-sessions", cron.JobConfig{
Title: "Clean up expired sessions",
Schedule: "0 * * * *", // Every hour
Endpoint: CleanupExpiredSessions,
})Schedule Formats
调度格式
| Field | Example | Description |
|---|---|---|
| | Simple interval. Must divide 24h evenly — |
| | Standard cron expression (5 fields, UTC). |
| 字段 | 示例 | 说明 |
|---|---|---|
| | 简单间隔。必须能整除24小时—— |
| | 标准cron表达式(5个字段,UTC时间)。 |
Common cron expressions
常用cron表达式
| Cron | Meaning |
|---|---|
| Every hour, on the hour |
| Daily at 02:00 UTC |
| Weekly on Sunday at midnight UTC |
| 04:00 UTC on the 15th of each month |
| Cron表达式 | 含义 |
|---|---|
| 每小时整点执行 |
| 每天UTC时间02:00执行 |
| 每周日午夜UTC时间执行 |
| 每月15日UTC时间04:00执行 |
Important behaviour
重要行为
- Cron jobs do not execute when running locally with . Only deployed environments fire crons.
encore run - The cron endpoint should be so it can't be triggered externally — only the cron scheduler should call it.
private - All times in are UTC. Convert from local time when designing the schedule.
Schedule - The endpoint must be defined at module load — declare it before the reference.
cron.NewJob
- 在本地使用运行时,Cron任务不会执行。 仅在已部署的环境中才会触发Cron任务。
encore run - Cron端点应设置为,这样就无法从外部触发——只能由Cron调度器调用。
private - 中的所有时间均为UTC时间。设计调度计划时请从本地时间转换为UTC时间。
Schedule - 端点必须在模块加载时定义——在引用之前声明它。
cron.NewJob
Guidelines
指导原则
- Use for "run on a regular interval" (must divide 24h).
Every - Use for specific times of day or days of week.
Schedule - Keep endpoint logic idempotent: a cron may fire late or be retried in a redeploy window.
- For event-driven background work (not time-driven), use the skill instead.
encore-go-pubsub
- 对于“按固定间隔运行”的任务使用(必须能整除24小时)。
Every - 对于特定时间段或星期几的任务使用。
Schedule - 保持端点逻辑的幂等性:Cron任务可能会延迟触发,或者在重新部署窗口中被重试。
- 对于事件驱动的后台任务(非时间驱动),请改用技能。
encore-go-pubsub