Skip to content

Commit 8122db5

Browse files
committed
Don't schedule alarms at night
1 parent 5e71c41 commit 8122db5

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

packages/server/src/worker.ts

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,25 @@ export class TinyDO extends WsServerDurableObject<Env> {
4040
}
4141

4242
async alarm(alarmInfo?: AlarmInvocationInfo) {
43-
this.ctx.storage.setAlarm(Date.now() + this.currentInterval)
43+
const currentHour = new Date().getUTCHours()
44+
let nextAlarm = Date.now() + this.currentInterval
45+
46+
// If it's no longer daytime, set the alarm for 06:00 UTC
47+
if (currentHour < 6 || currentHour > 21) {
48+
const nextAlarmDate = new Date()
49+
nextAlarmDate.setUTCHours(6, 0, 0, 0)
50+
nextAlarm = nextAlarmDate.getTime()
51+
52+
if (currentHour > 21) {
53+
console.log("It's too late in the evening. Setting alarm for tomorrow", nextAlarmDate.toISOString())
54+
nextAlarmDate.setUTCDate(nextAlarmDate.getUTCDate() + 1)
55+
nextAlarm = nextAlarmDate.getTime()
56+
} else {
57+
console.log("It's too early in the morning. Setting alarm for 06:00 UTC", nextAlarmDate.toISOString())
58+
}
59+
}
60+
61+
this.ctx.storage.setAlarm(nextAlarm)
4462
await this.sync()
4563
}
4664

0 commit comments

Comments
 (0)