Hmm, are you maybe setting the alarm to

Hmm, are you maybe setting the alarm to run in the constructor? Alternatively, are you calling the alarm() handler directly somewhere in your DO code?
5 Replies
jcheese
jcheese•4w ago
hmm. basically I have this:
private async scheduleNextPost() {
const randomHours = 2 + Math.floor(Math.random() * 7);
const milliseconds = randomHours * 60 * 60 * 1000;
await this.ctx.storage.setAlarm(Date.now() + milliseconds);
}

async alarm() {
await this.doSomething();
await this.scheduleNextPost();
}
private async scheduleNextPost() {
const randomHours = 2 + Math.floor(Math.random() * 7);
const milliseconds = randomHours * 60 * 60 * 1000;
await this.ctx.storage.setAlarm(Date.now() + milliseconds);
}

async alarm() {
await this.doSomething();
await this.scheduleNextPost();
}
is this even the right approach to have a randomly scheduled cron jobs 😅 ? and fyi no, im not calling the alarm() handler anywhere Im using the agents-starter if that helps
Milan
MilanOP•4w ago
1. How do you know your alarm handler is running? (Just curious) 2. Do you call scheduleNextPost() anywhere else other than the alarm()? 3. Is there any other place that sets the alarm?
jcheese
jcheese•4w ago
1. console.logging 2. no. weirdly, even when commenting out scheduleNextPost entirely, the alarm gets called everytime I reload 3. nope
nick
nick•4w ago
Found the issue, in case this comes up for anyone else in the future using the CF Agents sdk. The alarm method is overridden to be called in the constructor: https://github.com/cloudflare/agents/blob/main/packages/agents/src/index.ts#L319 So the agent class specific schedule method needs to be used instead. https://developers.cloudflare.com/agents/api-reference/schedule-tasks/
Cloudflare Docs
Schedule tasks
An Agent can schedule tasks to be run in the future by calling this.schedule(when, callback, data), where when can be a delay, a Date, or a cron string; callback the function name to call, and data is an object of data to pass to the function.
Milan
MilanOP•4w ago
Great find @nick!

Did you find this page helpful?