name: automation description: “调度cron作业、管理webhooks并自动化重复任务” emoji: “⏰”
自动化 - 完整API参考
使用cron表达式调度重复任务、管理传入webhooks并自动化工作流。
聊天命令
Cron作业
/cron list # 列出所有计划任务
/cron add "0 9 * * *" "扫描套利" # 添加每日9点任务
/cron add "*/30 * * * *" "检查价格" # 每30分钟
/cron remove <job-id> # 移除任务
/cron enable <job-id> # 启用任务
/cron disable <job-id> # 禁用任务
/cron run <job-id> # 立即运行任务
/cron history <job-id> # 查看运行历史
Webhooks
/webhook list # 列出webhooks
/webhook add <name> <url> # 添加webhook端点
/webhook remove <name> # 移除webhook
/webhook test <name> # 发送测试负载
/webhook logs <name> # 查看webhook日志
心跳监控
/heartbeat config --interval 60 # 设置心跳间隔
/heartbeat status # 查看心跳状态
/heartbeat enable # 启用心跳
/heartbeat disable # 禁用心跳
TypeScript API参考
Cron调度器
import { createCronScheduler } from 'clodds/automation';
const cron = createCronScheduler({
timezone: 'America/New_York',
autoStart: true,
});
// 添加任务
const jobId = cron.addJob({
name: 'daily-arb-scan',
schedule: '0 9 * * *', // 每日9点
task: async () => {
console.log('运行套利扫描...');
// 你的逻辑在这里
},
enabled: true,
});
// 列出任务
const jobs = cron.listJobs();
for (const job of jobs) {
console.log(`${job.id}: ${job.name} (${job.schedule})`);
console.log(` 下次运行: ${job.nextRun}`);
console.log(` 启用状态: ${job.enabled}`);
}
// 移除任务
cron.removeJob(jobId);
// 启用/禁用
cron.enableJob(jobId);
cron.disableJob(jobId);
// 立即运行
await cron.runJob(jobId);
// 获取历史
const history = cron.getHistory(jobId, { limit: 10 });
for (const run of history) {
console.log(`${run.timestamp}: ${run.status} (${run.duration}ms)`);
}
Cron表达式
| 表达式 | 描述 |
|---|---|
* * * * * |
每分钟 |
0 * * * * |
每小时 |
0 9 * * * |
每日9点 |
0 9 * * 1-5 |
工作日9点 |
*/15 * * * * |
每15分钟 |
0 0 1 * * |
每月第一天 |
Webhook管理器
import { createWebhookManager } from 'clodds/automation';
const webhooks = createWebhookManager({
secret: process.env.WEBHOOK_SECRET,
validateSignatures: true,
});
// 注册webhook端点
webhooks.register({
name: 'trade-alerts',
handler: async (payload) => {
console.log('收到:', payload);
// 处理webhook
return { status: 'ok' };
},
validatePayload: (payload) => {
return payload.type && payload.data;
},
});
// 获取webhook URL
const url = webhooks.getUrl('trade-alerts');
console.log(`Webhook URL: ${url}`);
// 发送测试
await webhooks.test('trade-alerts', {
type: 'test',
data: { message: 'Hello' },
});
// 查看日志
const logs = webhooks.getLogs('trade-alerts', { limit: 10 });
for (const log of logs) {
console.log(`${log.timestamp}: ${log.status}`);
console.log(` 负载: ${JSON.stringify(log.payload)}`);
}
// 移除webhook
webhooks.remove('trade-alerts');
心跳服务
import { createHeartbeatService } from 'clodds/automation';
const heartbeat = createHeartbeatService({
intervalMs: 60000, // 1分钟
endpoint: 'https://healthcheck.example.com/ping',
onFailure: (error) => {
console.error('心跳失败:', error);
},
});
// 启动
heartbeat.start();
// 获取状态
const status = heartbeat.getStatus();
console.log(`上次ping: ${status.lastPing}`);
console.log(`失败次数: ${status.failures}`);
console.log(`正常运行时间: ${status.uptime}%`);
// 停止
heartbeat.stop();
示例自动化
每日套利扫描
cron.addJob({
name: 'daily-arb',
schedule: '0 9,12,15,18 * * *', // 9点、12点、15点、18点
task: async () => {
const opportunities = await opportunityFinder.scan();
if (opportunities.length > 0) {
await notify(`找到 ${opportunities.length} 个套利机会`);
}
},
});
投资组合快照
cron.addJob({
name: 'portfolio-snapshot',
schedule: '0 0 * * *', // 每日午夜
task: async () => {
const portfolio = await trading.getPortfolio();
await database.saveSnapshot({
timestamp: Date.now(),
value: portfolio.totalValue,
positions: portfolio.positions.length,
});
},
});
外部信号Webhook
webhooks.register({
name: 'external-signals',
handler: async (payload) => {
if (payload.signal === 'buy') {
await executor.marketBuy({
platform: 'polymarket',
marketId: payload.marketId,
side: 'YES',
size: 100,
});
}
return { executed: true };
},
});
最佳实践
- 使用有意义的任务名称 - 便于后期识别
- 设置适当的间隔 - 避免API滥用
- 优雅处理失败 - 添加重试逻辑
- 监控任务历史 - 检查失败情况
- 验证webhook负载 - 防止坏数据
- 使用心跳监控 - 了解系统状态