纯单机架构
移除多节点集群、UDP 自动发现、主备故障转移与 Server Groups,消除分布式状态同步复杂度,所有作业在本机单进程引擎内调度。
Documentation
涵盖快速部署、CLI 参数、cronicle.yaml 全量配置、调度/链式/监控/RBAC 用法、自定义插件编写协议、REST API 与架构决策。
Cronicle Go 编译为单个无外部依赖的可执行文件(内嵌 Vue 3 SPA 与纯 Go WASM SQLite),复制即可直接启动。
cronicle.yaml(使用相对路径 data、logs、queue),并初始化 data/cronicle.db、默认分类 general 与三大原生内置插件。admin 时,会生成 12 位随机密码 并打印到终端。建议登录后立即在「个人账户」或「管理后台」修改密码。http://127.0.0.1:3012。Windows 下默认自动打开浏览器(可通过 --no-open 禁止),Linux 始终不自动打开浏览器。cronicle.yaml、data/、logs/ 与可执行文件到新服务器即可完成迁移。Cronicle Go compiles into a single self-contained binary with embedded Vue 3 assets and pure-Go WASM SQLite—copy and run directly.
cronicle.yaml with portable relative paths (data, logs, queue), creates data/cronicle.db, and seeds the general category and three native plugins.admin user is created with a randomly generated 12-character password printed to stdout. Change it after first sign-in.http://127.0.0.1:3012 by default. Windows opens the default browser automatically unless --no-open is passed; Linux never auto-opens.cronicle.yaml, data/, and logs/.# Windows (PowerShell / CMD)
.\cronicle.exe
# Linux (listen on all interfaces + external base URL behind reverse proxy)
./cronicle-linux-amd64 -l 0.0.0.0 -p 3012 --base-url https://cron.example.com
# Cross-compile single binaries from source (outputs to dist/)
.\build.ps1 # Windows PowerShell
./build.sh # Linux / macOS / Git Bash
命令行参数优先级高于配置文件,适用于容器化、systemd 托管、多实例端口隔离与调试排障场景。
CLI flags override values in cronicle.yaml, ideal for systemd services, containers, and quick debugging.
cronicle [flags]
cronicle version
-c, --config string Path to config file (.yaml / .yml / .json)
-l, --listen string Listen address (127.0.0.1 or 0.0.0.0 only)
-p, --port int HTTP/HTTPS port (default 3012)
-d, --data-dir string Data directory path
--base-url string External base URL (for Webhook/notification links)
--tls-cert string TLS certificate path
--tls-key string TLS private key path
--no-open Do not open browser automatically on startup
--debug Enable debug logging (debug_level=9)
-v, --version Print version information
__runner:当事件启用 Detached 分离模式时,调度引擎会以 cronicle __runner 自举启动独立进程组执行作业,该子命令仅供内部调用,无需手动执行。
__runner Subcommand: When an event runs in Detached mode, the engine spawns cronicle __runner in an independent process group. This subcommand is managed internally by the scheduler.
未指定 -c/--config 时按顺序查找 cronicle.yaml → cronicle.yml → config.json。data_dir、db_path、log_dir、queue_dir 均支持相对路径(生产模式相对于可执行文件目录,dev 构建标签模式下相对于当前工作目录)。
When -c/--config is omitted, Cronicle Go searches cronicle.yaml → cronicle.yml → config.json. data_dir, db_path, log_dir, and queue_dir accept relative paths (resolved against the executable directory in production, or CWD under the dev build tag).
| 配置项 | 默认值 | 说明 |
|---|---|---|
listen_addr / http_port | 127.0.0.1 / 3012 | 监听网卡地址(仅允许 127.0.0.1 或 0.0.0.0)与服务端口。 |
base_app_url | "" | 外部访问基地址(如 https://cron.example.com),用于生成邮件/Webhook 中的详情跳转链接。 |
data_dir / db_path / log_dir / queue_dir | data / "" / logs / queue | 数据目录、自定义 SQLite 路径(默认 <data_dir>/cronicle.db)、作业日志目录与分离作业队列目录。 |
secret_key | CHANGE_ME | Session 与 API Key 的 HMAC 签名密钥。留空或为 CHANGE_ME 时每次启动随机生成(会导致重启后会话失效),生产环境务必改为 openssl rand -hex 32。 |
tls_enabled / tls_cert_file / tls_key_file | false / "" / "" | 启用内置 HTTPS 服务;若需反向代理终止 TLS,保持 false 即可。 |
max_jobs / track_manual_jobs | 0 / false | 全局并发作业上限(0 表示不限制),以及手动触发作业是否计入全局限流与调度统计。 |
job_memory_max / job_memory_sustain | 1073741824 (1 GB) / 0 | 全局默认进程树 RSS 内存上限(字节)与持续超限判定秒数。 |
job_cpu_max / job_cpu_sustain / job_log_max_size | 0 / 0 / 0 | 全局默认 CPU 百分比上限、持续秒数与单作业日志文件大小上限(字节,0 不限制)。 |
job_env | {} | 注入给所有插件子进程的全局环境变量键值对。 |
scheduler_startup_grace / maintenance_time | 3 / "04:00" | 启动宽限秒数与每日自动清理过期作业日志/历史记录的时间(HH:MM,保留 job_data_expire_days 天)。 |
session_expire_days / max_failed_logins_per_hour | 30 / 10 | 登录会话有效期与单小时失败登录限流次数;free_accounts 与 allow_password_recovery 控制自助注册与找回开关。 |
universal_web_hook / web_hook_text_templates | "" / 默认模板 | 全局 Webhook URL 与 job_start/job_complete/job_failure/job_launch_failure 文本模板,支持 web_hook_custom_data 与 web_hook_config_keys。 |
smtp.* | enabled: false | 邮件配置:hostname、port、username、password、from、tls_mode(none/starttls/tls)、skip_cert_verify、max_emails_per_day。 |
| Key | Default | Description |
|---|---|---|
listen_addr / http_port | 127.0.0.1 / 3012 | Bind IP (127.0.0.1 or 0.0.0.0 only) and HTTP/HTTPS port. |
base_app_url | "" | External base URL used to build job_details_url and edit_event_url in notifications. |
data_dir / db_path / log_dir / queue_dir | data / "" / logs / queue | Data dir, optional custom SQLite path (defaults to <data_dir>/cronicle.db), job log dir, and detached queue dir. |
secret_key | CHANGE_ME | HMAC signing key for sessions and API keys. If empty or CHANGE_ME, a random key is generated per boot (invalidating sessions). Use openssl rand -hex 32 in production. |
tls_enabled / tls_cert_file / tls_key_file | false / "" / "" | Enable direct HTTPS serving; keep false when terminating TLS at Nginx/Caddy. |
max_jobs / track_manual_jobs | 0 / false | Global concurrent job cap (0 = unlimited) and whether manual runs count toward limits. |
job_memory_max / job_memory_sustain | 1073741824 (1 GB) / 0 | Default process-tree RSS memory limit (bytes) and sustain duration (seconds). |
job_cpu_max / job_cpu_sustain / job_log_max_size | 0 / 0 / 0 | Default CPU% limit, sustain seconds, and max log file size per job (bytes, 0 = unlimited). |
job_env | {} | Global key/value environment variables injected into every plugin subprocess. |
scheduler_startup_grace / maintenance_time | 3 / "04:00" | Startup grace seconds and daily maintenance time (HH:MM) to prune jobs older than job_data_expire_days. |
session_expire_days / max_failed_logins_per_hour | 30 / 10 | Session TTL and login rate limit per hour; free_accounts and allow_password_recovery toggle self-registration/recovery. |
universal_web_hook / web_hook_text_templates | "" / Built-in | Global webhook URL, templates (job_start, job_complete, job_failure, job_launch_failure), web_hook_custom_data, and web_hook_config_keys. |
smtp.* | enabled: false | SMTP mailer settings: hostname, port, username, password, from, tls_mode (none/starttls/tls), skip_cert_verify, max_emails_per_day. |
Cronicle Go 的调度循环按分钟推进每个已启用事件的游标(Cursor),并按事件配置的时区(如 Asia/Shanghai)匹配日历条件。
years、months(1-12)、days(1-31)、weekdays(0-6,0 为周日)、hours(0-23)、minutes(0-59)。任意维度留空表示“不限制该维度”;空对象 {} 表示每分钟触发;timing: null 表示按需执行(On-Demand),仅能手动、API 或 Chain Reaction 触发。POST /api/v1/crontab/parse 可直接导入标准 5 段式 Crontab(分 时 日 月 周),支持 *、,、-、/ 步长、月份英文缩写(jan..dec)、星期英文缩写(sun..sat)及周日 7→0 归一化,同时支持快捷时间预设(如“今日 21:50”)。catch_up 后,若服务停机或事件被禁用一段时间,恢复后引擎会按历史分钟游标顺序补跑错过的时间点;配合「Time Machine」可将任意事件的调度游标重置到指定历史时间戳重新回放。max_jobs → 分类 max_children → 事件 max_children。若达到并发上限且开启 queue: true,新触发的请求会写入 SQLite 持久化 event_queue 队列(受 queue_max 限制),待前序作业结束自动按 FIFO 出队,也可在界面或通过 POST /api/v1/events/{id}/flush-queue 手动清空队列。The scheduler advances a per-event minute cursor and evaluates calendar rules in each event's configured IANA timezone (e.g., Asia/Shanghai).
years, months (1–12), days (1–31), weekdays (0–6, 0=Sunday), hours (0–23), and minutes (0–59). An empty array means wildcard; {} runs every minute; timing: null marks an On-Demand event (manual, API, or chained triggers only).POST /api/v1/crontab/parse, supporting *, ,, -, / steps, month aliases (jan..dec), weekday aliases (sun..sat), and 7→0 Sunday normalization, plus quick presets.catch_up is enabled, missed schedule minutes during downtime are backfilled sequentially on recovery. Time Machine lets you reset an event's cursor to any custom timestamp.max_jobs, category max_children, and event max_children. When busy and queue: true is set, triggers are persisted to SQLite event_queue (bounded by queue_max) and drained FIFO, or cleared via POST /api/v1/events/{id}/flush-queue.detached: true 后,作业由自举子命令 cronicle __runner 在独立进程组(Windows CREATE_NEW_PROCESS_GROUP / Unix Setpgid)中执行。主调度服务重启或升级时不会中断正在运行的分离作业;主服务重新启动后会自动扫描恢复接管其进度与完成状态归档。retries > 0,引擎会按 retry_delay 秒延迟后自动重新拉起同一作业(日志追加同一作业文件,不额外产生孤立失败记录)。chain)与失败下游(chain_error),插件运行时也可通过 stdout JSON 动态覆盖下游事件 ID。上游作业结束后,系统会将 chain_code、chain_description、chain_data 与 chain_params 传递给下游作业(详见插件协议与 HTTP 占位符)。cronicle __runner): Enabling detached: true launches the job in an isolated process group via cronicle __runner. Long-running jobs survive main server restarts and are automatically re-attached when the server comes back up.retries > 0 are rescheduled after retry_delay seconds, appending retry output to the same job log.chain) and failure (chain_error), or override them dynamically via plugin stdout JSON. Upstream chain_code, chain_description, chain_data, and chain_params flow automatically into the downstream job.cpu_limit / memory_limit 且持续达到 cpu_sustain / memory_sustain 秒,或作业总超时(timeout)、日志体积超过 log_max_size 时,会自动终止整个进程组并记录清晰的中止原因。/ws)毫秒级推送作业进度与控制台输出流;自动剥离终端 ANSI 颜色/光标转义序列(StripANSI)与 Windows GB18030 转码;支持一键复制日志、HMAC 签名令牌直链下载原始日志,以及基于 ECharts 6 的单作业耗时分解与历史 CPU/内存趋势图表。universal_web_hook。与原版 Cronicle 保持严格语义一致——作业失败时 JSON 载荷中的 action 字段仍为 "job_complete",但文本渲染会自动选择 job_failure 模板;若对应模板为空字符串则跳过发送。Payload 自动附带 text、content、message、base_app_url、job_details_url 与 edit_event_url,兼容企业微信、飞书、钉钉、Slack 等机器人。none(明文)、starttls 与隐式 tls(465 端口),支持 skip_cert_verify 自签证书与每日发信上限 max_emails_per_day;手动中止默认不发失败告警邮件(可通过 email_on_manual_abort: true 开启)。gopsutil/v4. Exceeding cpu_limit / memory_limit for cpu_sustain / memory_sustain seconds—or hitting timeout or log_max_size—cleanly terminates the whole process group./ws), supports one-click log copy and HMAC-signed log downloads, and plots ECharts performance breakdowns and resource trends.universal_web_hook endpoints. Matches original Cronicle semantics: failed jobs keep "action": "job_complete" while rendering the job_failure template, and payloads include text, content, message, job_details_url, and edit_event_url.none, starttls, and implicit tls (port 465), optional skip_cert_verify, and max_emails_per_day quota.create_events、edit_events、delete_events、run_events、abort_events、state_update 等功能权限,以及分类级别隔离权限(cat_limit 开关 + cat_<id> 白名单)。admin 权限、无法调用用户/分类/插件/审计等管理员接口、也无法通过 API Key 管理 API Key 本身;每次请求时其生效权限都会实时与所属用户的当前状态和权限取交集。create_events, edit_events, delete_events, run_events, abort_events, state_update) and category scoping (cat_limit + cat_<id>).admin privilege, cannot manage keys or call admin endpoints, and are intersected in real time with the owner's active status and privileges.Cronicle Go 使用 Go 原生重写了三大内置插件,系统启动时自动注册且受只读保护(Web UI 与 API 均禁止修改或删除)。
shellplug / builtin:shell)interpreter):支持 auto、cmd、powershell、bash、sh。Windows 下 auto 默认使用 cmd.exe(自动生成临时 .bat 并注入 chcp 65001 >nul 与 CRLF 换行);若脚本首行含 #!...bash 或 #!...sh 则自动切换对应解释器;选择 powershell 时自动设置控制台 UTF-8 输出编码。CRONICLE=1.0、JOB_ID、JOB_NOW、JOB_LOG_FILE、EVENT_ID、EVENT_TITLE 及全部 JOB_PARAM_*;脚本中单独打印一行百分比(如 50%)即可实时更新作业进度条。annotate 可为每行日志自动加上 [YYYY-MM-DD HH:MM:SS] 时间戳;勾选 json 后,单行合法 JSON({...})会按插件协议解析为进度/报告/链式更新。urlplug / builtin:url)GET、HEAD、POST、PUT、DELETE,可配请求头(每行 Key: Value)、请求体(data)、连接超时(connect_timeout,默认 10s)、请求超时(timeout,默认 30s)、跟随重定向(follow)与跳过 TLS 校验(ssl_cert_bypass)。[id]、[event]、[event_title]、[hostname]、[now]、[chain_code]、[chain_description] 及 [chain_data/字段名]。200–399 之间;可额外配置正则表达式 error_match(命中则失败)与 success_match(未命中则失败)。testplug / builtin:test)duration(支持固定秒数如 5 或随机区间如 3-8)、progress(上报模拟进度)、burn(分配并读写 32MB 内存模拟负载)与 action(模拟 Success / Failure / Crash 结果),并生成 Perf、Table 与 HTML 示例报告。Cronicle Go ships three native Go built-in plugins registered at startup and protected as read-only via both UI and API.
shellplug / builtin:shell)interpreter): Supports auto, cmd, powershell, bash, and sh. On Windows, auto defaults to cmd.exe (injecting chcp 65001 >nul) unless a #! shebang selects sh/bash; PowerShell enforces UTF-8 console encoding automatically.CRONICLE=1.0, JOB_ID, JOB_NOW, JOB_LOG_FILE, EVENT_ID, EVENT_TITLE, and JOB_PARAM_*. Printing a standalone percentage line like 50% updates job progress live.annotate to prepend timestamps to every log line, or json to interpret single-line JSON updates on stdout.urlplug / builtin:url)GET, HEAD, POST, PUT, DELETE, multiline headers, request data, connect_timeout (default 10s), timeout (default 30s), follow redirects, and ssl_cert_bypass.[id], [event], [event_title], [hostname], [now], [chain_code], [chain_description], and [chain_data/key] in URL, headers, and body.200–399 plus optional regex checks error_match and success_match.testplug / builtin:test)duration like 5 or 3-8), live progress, 32 MB memory burn, and Success / Failure / Crash outcomes while emitting sample Perf, Table, and HTML reports.Cronicle Go 的外部插件协议与原版 pixl-json-stream 语义兼容:调度器通过 stdin 传入一行完整 Job JSON,插件通过 stdout 逐行输出普通日志或控制指令 JSON。任何可读写标准输入输出的语言(Python、Node.js、Go、Rust、Bash、PowerShell 等)均可编写插件。
前往 管理后台 → 插件 → 新增插件,填写标题、可执行命令(command)、可选工作目录(cwd)与参数定义(params)。
command 可以填写完整命令(如 python3 /opt/plugins/sync.py --mode fast),也可以直接填写脚本路径(如 D:\scripts\etl.py 或含空格路径)。调度器按以下顺序自动解析执行器:
.exe/.com 直接运行,.bat/.cmd 自动包裹 cmd /c,.ps1 自动包裹 powershell -NoProfile -ExecutionPolicy Bypass -File;
chmod +x)的文件直接运行;
#!/usr/bin/env python3 等),自动解析解释器(Windows 下若无 python3 会自动回退查找 python);
.py → python3/python、.js/.mjs/.cjs → node、.sh → bash、.rb → ruby、.pl → perl、.php → php。command 字段支持单双引号传参,但严禁包含 Shell 管道与重定向字符(|、>、<、;、&);若需要复杂 Shell 管道组合,请使用内置 Shell Script 插件或将逻辑封装到脚本文件中再调用。
params)每个插件可配置多个参数字段,在创建/编辑事件时自动渲染为图形化表单控件,并透传给插件:
参数类型 (type) | 控件表现 | 常用附加字段 |
|---|---|---|
text | 单行文本输入框 | value(默认值)、size(宽度 1–40) |
textarea | 多行文本域(如 SQL、脚本、JSON 模板) | value(默认文本)、rows(行数 1–50) |
checkbox | 勾选开关(值一般为 0 / 1 或布尔值) | value(默认 0 未选中 / 1 选中) |
select | 下拉单选框 | items(选项数组,后台表单用逗号分隔填写)、value(默认选中项) |
hidden | 不在事件表单展示的隐藏固定参数 | value(固定传入值) |
stdin Job JSON 与环境变量)插件启动后,引擎会立即向子进程的 stdin 写入单行完整的 Job JSON 并关闭 stdin,同时自动注入环境变量:
CRONICLE=1.0、JOB_ID、JOB_NOW(调度 Unix 秒时间戳)、JOB_LOG_FILE、EVENT_ID、EVENT_TITLE,以及将 params 中每个键转换为大写的 JOB_PARAM_<KEY>(空格自动替换为下划线)。stdin JSON 常用字段:id、event、event_title、category、plugin、cwd、now、hostname、params(事件填写的参数对象)、chain_data(上游传递的任意结构化数据)、chain_params(上游覆盖的参数)、chain_code、chain_description。stdout JSON Lines 与退出判定)调度器逐行读取插件的 stdout(自动 UTF-8 / GB18030 转码):
{...} 单行 JSON 的 stdout 与全部 stderr 内容,均自动剥离 ANSI 控制符并实时写入作业日志流与 logs/jobs/<id>.log。{ 开头且以 } 结尾,并成功解析为 JSON 对象时,不会打印到普通日志,而是触发以下实时状态更新(请务必在每次 print 后 flush 输出缓冲区):| JSON 字段 | 类型 | 作用说明 |
|---|---|---|
progress | number (0.0 ~ 1.0) | 实时更新网页上的作业进度条(如 0.45 表示 45%)。 |
complete | 1 或 true | 标记插件完成态(通常与 code / description 一起输出)。 |
code | int | 结果状态码:0 表示成功,非 0 表示失败。若插件输出过带 code 的 JSON,则以最后一个 JSON code 为最终作业状态码;否则回退使用进程退出码(Exit Code)。 |
description | string | 结果摘要或失败原因说明(在历史列表与告警通知中展示)。 |
perf | object | 性能指标对象(如 {"total": 3.2, "db": 1.1, "api": 1.8}),作业详情页自动绘制 ECharts 性能分布图。 |
table | object | 结构化数据表:{"title": "...", "header": ["列1","列2"], "rows": [[...]], "caption": "..."}。 |
html | object | 自定义 HTML 报告:{"title": "...", "content": "<p>...</p>", "caption": "..."}。 |
chain / chain_error | string | 运行时动态指定成功或失败后要触发的下游事件 ID(覆盖事件静态配置)。 |
chain_data / chain_params | object | 向下游 Chain Reaction 事件传递上下文数据或参数覆盖。 |
notify_success / notify_fail | string | 运行时动态覆盖成功或失败的通知接收邮箱。 |
label | string | 为该次作业附加自定义徽标文本,在历史列表中高亮展示。 |
#!/usr/bin/env python3
import json
import sys
import time
def emit(payload: dict):
print(json.dumps(payload, ensure_ascii=False), flush=True)
def main():
# 1. 从 stdin 读取完整 Job JSON(单行)
raw = sys.stdin.readline()
job = json.loads(raw) if raw.strip() else {}
params = job.get("params", {})
chain_data = job.get("chain_data", {})
env = params.get("env", "prod")
dry_run = bool(int(params.get("dry_run", 0))) if str(params.get("dry_run", "")).isdigit() else bool(params.get("dry_run"))
print(f"[INFO] Start sync job={job.get('id')} env={env} dry_run={dry_run} prev_batch={chain_data.get('batch_id')}", flush=True)
start = time.time()
try:
# 2. 模拟分步处理并实时上报进度
for step, ratio in [("fetch", 0.35), ("transform", 0.70), ("commit", 1.0)]:
time.sleep(0.3)
print(f"[INFO] Stage {step} done", flush=True)
emit({"progress": ratio})
elapsed = round(time.time() - start, 3)
# 3. 上报性能耗时、表格/HTML 报告与下游链式数据
emit({
"complete": 1,
"code": 0,
"description": f"Synced 1280 orders to {env}",
"label": env.upper(),
"perf": {"total": elapsed, "fetch": 0.3, "transform": 0.3, "commit": 0.3},
"table": {
"title": "Sync Summary",
"header": ["Target", "Inserted", "Updated", "Skipped"],
"rows": [[env, 420, 860, 12]],
"caption": "Generated by sync_orders.py"
},
"html": {
"title": "Execution Note",
"content": f"<p>Batch <strong>{job.get('id')}</strong> finished cleanly.</p>"
},
"chain_data": {"batch_id": job.get("id"), "rows": 1280}
})
except Exception as exc:
emit({"complete": 1, "code": 1, "description": f"Sync failed: {exc}"})
sys.exit(1)
if __name__ == "__main__":
main()
#!/usr/bin/env node
import readline from 'node:readline';
const emit = (obj) => process.stdout.write(JSON.stringify(obj) + '\n');
const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
rl.once('line', async (line) => {
rl.close();
const job = JSON.parse(line || '{}');
console.log(`[Node Plugin] Running ${job.event_title} (target=${job.params?.target || 'default'})`);
emit({ progress: 0.5 });
await new Promise((r) => setTimeout(r, 400));
emit({
complete: 1,
code: 0,
description: 'Node.js task succeeded',
perf: { total: 0.41 },
chain_data: { ok: true, job_id: job.id }
});
});
package main
import (
"bufio"
"encoding/json"
"fmt"
"os"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
scanner.Buffer(make([]byte, 64*1024), 4*1024*1024)
var job struct {
ID string `json:"id"`
Params map[string]any `json:"params"`
}
if scanner.Scan() {
_ = json.Unmarshal(scanner.Bytes(), &job)
}
fmt.Printf("Processing job %s\n", job.ID)
enc := json.NewEncoder(os.Stdout)
_ = enc.Encode(map[string]any{"progress": 0.5})
_ = enc.Encode(map[string]any{
"complete": 1,
"code": 0,
"description": "Go plugin finished",
"perf": map[string]float64{"total": 0.12},
})
}
Cronicle Go implements a pixl-json-stream-compatible external plugin contract: the scheduler writes one full Job JSON line to stdin, and your plugin emits plain log lines or JSON Lines control messages to stdout. Any language capable of reading stdin and writing stdout works.
Go to Admin → Plugins → Add Plugin, set a title, command, optional cwd, and UI parameter definitions (params).
python3 /opt/plugins/sync.py --mode fast) or a direct script path (even with spaces). The runner resolves executors in order:
.exe/.com directly, .bat/.cmd via cmd /c, .ps1 via powershell -NoProfile -ExecutionPolicy Bypass -File;
chmod +x) on Unix;
#!/usr/bin/env python3, falling back from python3 to python on Windows if needed);
.py → python3/python, .js/.mjs/.cjs → node, .sh → bash, .rb → ruby, .pl → perl, .php → php.|, >, <, ;, &) are strictly rejected in external plugin commands. Put pipelines inside a script file or use the built-in Shell Script plugin.
params)type | UI Control | Extra Fields |
|---|---|---|
text | Single-line input | value (default), size (1–40) |
textarea | Multi-line editor (SQL, scripts, JSON) | value (default text), rows (1–50) |
checkbox | Boolean toggle (0 / 1) | value (0 unchecked / 1 checked) |
select | Dropdown select | items (option list), value (default item) |
hidden | Hidden fixed parameter | value (static value) |
stdin Job JSON & Environment)CRONICLE=1.0, JOB_ID, JOB_NOW, JOB_LOG_FILE, EVENT_ID, EVENT_TITLE, and JOB_PARAM_<KEY> (uppercase with spaces replaced by underscores).stdin Payload: One line of JSON containing id, event, event_title, params, chain_data, chain_params, chain_code, chain_description, now, cwd, and hostname, followed by EOF.stdout JSON Lines & Exit Status)Any non-JSON stdout line and all stderr lines are decoded (UTF-8 / GB18030), ANSI-stripped, and streamed to the job log. Lines trimmed to {...} that parse as JSON trigger live updates (always flush stdout after printing):
| JSON Field | Type | Behavior |
|---|---|---|
progress | number (0.0–1.0) | Updates the live job progress bar. |
complete | 1 or true | Marks completion update alongside code/description. |
code | int | 0 = success, non-zero = failure. When emitted via JSON, the last JSON code overrides the process exit code. |
description | string | Summary or error message shown in history and notifications. |
perf | object | Timing breakdown (e.g., {"total": 3.2, "db": 1.1}) rendered as an ECharts breakdown chart. |
table | object | Structured table: {"title", "header": [...], "rows": [[...]], "caption"}. |
html | object | Custom HTML report: {"title", "content", "caption"}. |
chain / chain_error | string | Dynamically override downstream success/error event IDs. |
chain_data / chain_params | object | Pass structured data or parameter overrides to downstream chained events. |
notify_success / notify_fail | string | Override notification email recipients for this run. |
label | string | Attach a custom badge label to the job record. |
#!/usr/bin/env python3
import json
import sys
import time
def emit(payload: dict):
print(json.dumps(payload, ensure_ascii=False), flush=True)
def main():
raw = sys.stdin.readline()
job = json.loads(raw) if raw.strip() else {}
params = job.get("params", {})
chain_data = job.get("chain_data", {})
env = params.get("env", "prod")
print(f"[INFO] Start sync job={job.get('id')} env={env} prev_batch={chain_data.get('batch_id')}", flush=True)
start = time.time()
try:
for step, ratio in [("fetch", 0.35), ("transform", 0.70), ("commit", 1.0)]:
time.sleep(0.3)
print(f"[INFO] Stage {step} done", flush=True)
emit({"progress": ratio})
elapsed = round(time.time() - start, 3)
emit({
"complete": 1,
"code": 0,
"description": f"Synced 1280 orders to {env}",
"label": env.upper(),
"perf": {"total": elapsed, "fetch": 0.3, "transform": 0.3, "commit": 0.3},
"table": {
"title": "Sync Summary",
"header": ["Target", "Inserted", "Updated", "Skipped"],
"rows": [[env, 420, 860, 12]],
"caption": "Generated by sync_orders.py"
},
"html": {
"title": "Execution Note",
"content": f"<p>Batch <strong>{job.get('id')}</strong> finished cleanly.</p>"
},
"chain_data": {"batch_id": job.get("id"), "rows": 1280}
})
except Exception as exc:
emit({"complete": 1, "code": 1, "description": f"Sync failed: {exc}"})
sys.exit(1)
if __name__ == "__main__":
main()
#!/usr/bin/env node
import readline from 'node:readline';
const emit = (obj) => process.stdout.write(JSON.stringify(obj) + '\n');
const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
rl.once('line', async (line) => {
rl.close();
const job = JSON.parse(line || '{}');
console.log(`[Node Plugin] Running ${job.event_title} (target=${job.params?.target || 'default'})`);
emit({ progress: 0.5 });
await new Promise((r) => setTimeout(r, 400));
emit({
complete: 1,
code: 0,
description: 'Node.js task succeeded',
perf: { total: 0.41 },
chain_data: { ok: true, job_id: job.id }
});
});
package main
import (
"bufio"
"encoding/json"
"fmt"
"os"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
scanner.Buffer(make([]byte, 64*1024), 4*1024*1024)
var job struct {
ID string `json:"id"`
Params map[string]any `json:"params"`
}
if scanner.Scan() {
_ = json.Unmarshal(scanner.Bytes(), &job)
}
fmt.Printf("Processing job %s\n", job.ID)
enc := json.NewEncoder(os.Stdout)
_ = enc.Encode(map[string]any{"progress": 0.5})
_ = enc.Encode(map[string]any{
"complete": 1,
"code": 0,
"description": "Go plugin finished",
"perf": map[string]float64{"total": 0.12},
})
}
支持 Session Cookie(cronicle_session)、Authorization: Bearer、X-Session-ID 以及 X-API-Key(或 query 参数 api_key)。管理员接口强制要求管理员登录会话,API 密钥无法拥有管理员权限,且实时取所属用户的权限交集。Web 控制台内置交互式 API 文档页面(/#/api-docs)。
Supports Session Cookie (cronicle_session), Authorization: Bearer, X-Session-ID, and X-API-Key (or api_key query param). Admin endpoints require an active admin login session; API keys can never hold admin privileges and are intersected with their owner's live privileges. Built-in interactive docs are available at /#/api-docs.
# Health & Auth
GET /api/v1/health GET /api/v1/app/config
POST /api/v1/auth/login POST /api/v1/auth/logout
GET /api/v1/auth/me PUT /api/v1/account
# Personal API Keys & Admin Resources (Users / Categories / Plugins)
GET/POST/PUT/DELETE /api/v1/api-keys
GET/POST/PUT/DELETE /api/v1/users (admin session only)
GET/POST/PUT/DELETE /api/v1/categories (write: admin session only)
GET/POST/PUT/DELETE /api/v1/plugins (write: admin session only)
# Events, Scheduling & Jobs
GET/POST/PUT/DELETE /api/v1/events POST /api/v1/events/{id}/run
POST /api/v1/events/{id}/flush-queue GET /api/v1/events/{id}/history
POST /api/v1/crontab/parse
GET /api/v1/jobs/active GET /api/v1/jobs/history
GET/PUT/DELETE /api/v1/jobs/{id} POST /api/v1/jobs/{id}/abort
GET /api/v1/jobs/{id}/log
# System State & Real-time WebSocket
GET/PUT /api/v1/system/state GET /api/v1/system/status
GET /api/v1/system/activity GET /ws (Native WebSocket)
移除多节点集群、UDP 自动发现、主备故障转移与 Server Groups,消除分布式状态同步复杂度,所有作业在本机单进程引擎内调度。
采用 ncruces/go-sqlite3(WASM 驱动,WAL 模式)零 CGO 存储结构化数据,作业大体积控制台输出保留为独立 .log 文件。
使用语义化的 /api/v1/* REST JSON API 与原生 /ws 替代原版 /api/app/* RPC 与 Socket.IO。
三大内置插件由 Go 原生实现;Detached 模式通过自举子命令 __runner 启动独立进程组保活,并由 gopsutil 监控进程树。
Removes multi-node clustering, UDP auto-discovery, primary/backup failover, and Server Groups so scheduling and concurrency stay simple and instant.
Uses ncruces/go-sqlite3 (WASM driver, WAL mode) with CGO_ENABLED=0 for structured state while keeping streaming logs in logs/jobs/*.log.
Replaces legacy /api/app/* RPC and Socket.IO with typed RESTful /api/v1/* JSON endpoints and standard WebSocket /ws.
Implements Shell, HTTP, and Test plugins natively in Go, runs detached jobs via cronicle __runner, and monitors process trees with gopsutil.
Cronicle Go 的设计与核心心智模型灵感源自经典开源项目 jhuckaby/Cronicle(MIT License)。本项目由 Go + Vue 3 从零重构,所用核心开源依赖如下:
| 组件 / 模块 | 用途 | 协议 |
|---|---|---|
github.com/ncruces/go-sqlite3 | 纯 Go + WASM 嵌入式 SQLite 驱动(零 CGO) | MIT |
github.com/gorilla/websocket | 服务端原生 WebSocket 实时推流 | BSD-2-Clause |
github.com/shirou/gopsutil/v4 | 跨平台主机与子进程树 CPU / 内存资源采集 | BSD-3-Clause |
golang.org/x/crypto & golang.org/x/text | 密码哈希与 Windows GB18030→UTF-8 编码转换 | BSD-3-Clause |
gopkg.in/yaml.v3 | cronicle.yaml 配置文件解析与持久化 | MIT / Apache-2.0 |
vue / pinia / vue-router / vue-i18n | 内嵌单页控制台核心前端框架与双语状态管理 | MIT |
element-plus & @element-plus/icons-vue | 控制台 UI 组件库与图标集 | MIT |
echarts & axios | 作业性能/资源趋势可视化图表与 HTTP 客户端 | Apache-2.0 / MIT |
Cronicle Go is inspired by jhuckaby/Cronicle (MIT License) and rewritten from scratch in Go + Vue 3. Key open-source dependencies include:
| Package / Module | Purpose | License |
|---|---|---|
github.com/ncruces/go-sqlite3 | Pure-Go WASM embedded SQLite driver (no CGO) | MIT |
github.com/gorilla/websocket | Native WebSocket real-time streaming | BSD-2-Clause |
github.com/shirou/gopsutil/v4 | Cross-platform host & process-tree CPU/memory telemetry | BSD-3-Clause |
golang.org/x/crypto & golang.org/x/text | Password hashing and GB18030→UTF-8 transcoding | BSD-3-Clause |
gopkg.in/yaml.v3 | cronicle.yaml parsing and persistence | MIT / Apache-2.0 |
vue / pinia / vue-router / vue-i18n | Embedded SPA framework, state store, routing, and i18n | MIT |
element-plus & @element-plus/icons-vue | Web console UI components and icons | MIT |
echarts & axios | Performance/telemetry charts and HTTP client | Apache-2.0 / MIT |
带有 Timing 时间规则、分类归属、插件引用与并发/资源限制的可调度任务模板;timing: null 表示按需执行。
Event 的单次运行实例,拥有独立的执行状态、PID、进程树 CPU/内存指标、控制台输出与 perf/table/html 报告。
停机或禁用期间错过的到期调度按序补跑(Catch Up),或重置事件基准游标时钟重放调度(Time Machine)。
通过 cronicle __runner 在独立进程组保活运行的分离作业,以及前置作业成功/失败后自动触发下游的链式编排。
用于组织事件的逻辑分组,可统一配置默认分类并发上限(max_children)、资源限额与通知策略,并支持按用户做 RBAC 分类隔离。
实际承载作业执行逻辑的执行器,分为只读原生内置插件(builtin:*)与遵循 stdin/stdout JSON Lines 协议的外部插件。
A schedulable task template carrying Timing rules, category membership, plugin reference, and resource limits; timing: null means On-Demand.
A single execution instance of an Event with its own PID, process-tree CPU/memory metrics, console log, and perf/table/html reports.
Catch Up backfills missed minutes after downtime; Time Machine resets an event's scheduler cursor to any timestamp.
Detached jobs survive server restarts via __runner; Chain Reaction triggers downstream events on success or error with chain_data.
Logical grouping for events that provides shared max_children, resource limits, alert defaults, and per-user RBAC isolation.
The executor behind each job—either a read-only native Go built-in (builtin:*) or an external executable/script using the JSON Lines protocol.