-
Notifications
You must be signed in to change notification settings - Fork 663
Description
I have a timer table with a scheduled reducer with the following columns where currently its only calculating the delta time since last reducer run for planned use on movement calculations based on delta time.
export const mobilitySystemTable = table(
{ name: "mobility_system", public: false, scheduled: "mobility_system_timer" },
{
scheduled_id: t.u64().primaryKey().autoInc(),
scheduled_at: t.scheduleAt(),
last_timestamp: t.timestamp(),
}
);
last_timestamp gets set to ctx.timestamp when the reducer runs as well as within the module init function.
Here is how I am initializing the table within the init function.
ctx.db.mobilitySystem.insert({
scheduled_id: 0n,
scheduled_at: {
tag: "Interval",
value: TimeDuration.fromMillis(5 * 1000), // every 5 seconds
},
last_timestamp: ctx.timestamp,
});
With this following print statement I am seeing times off when the module starts up either through rebuild from spacetime dev or just me manually starting spacetimedb for the day.
spacetimedb.reducer('mobility_system_timer', {timer: mobilitySystemTable.rowType}, (ctx, { timer }) => {
if(!ctx.sender.equals(ctx.identity)) {
console.warn(`Ignoring mobility_system_timer triggered by another identity: ${ctx.identity} != ${ctx.sender}`);
return;
}
const deltaTimeSecs = ctx.timestamp.since(timer.last_timestamp).millis / 1000.0;
if(deltaTimeSecs <= 4.0 || deltaTimeSecs >= 6.0) {
console.log(`mobility_system_timer (ctx.timestamp) ${ctx.timestamp.toDate()} - (timer.last_timestamp) ${timer.last_timestamp.toDate()} = ${ctx.timestamp.since(timer.last_timestamp).toString()}`);
}
ctx.db.mobilitySystem.scheduled_id.update({
...timer,
last_timestamp: ctx.timestamp,
});
});
I confirmed via the psql connection to my local spacetime that there is only one row in my scheduled reducer:
something-some-####=> select * from mobility_system;
scheduled_id | scheduled_at | last_timestamp
--------------+----------------------------------------------------+----------------------------------
1 | {"Interval": {"__time_duration_micros__": "PT5S"}} | 2025-12-19T14:28:12.277062+00:00
(1 row)
This after a manual clean and rerun spacetime dev:
2025-12-19T14:18:40.482298Z INFO: mobility_system_timer spacetimedb_module:4348: mobility_system_timer (ctx.timestamp) Fri Dec 19 2025 08:18:40 GMT-0600 () - (timer.last_timestamp) Fri Dec 19 2025 08:18:32 GMT-0600 () = +8.098119
This happened after changing a line of code and spacetime dev rebuilt and published for me:
2025-12-19T14:19:29.914289Z INFO: mobility_system_timer spacetimedb_module:4348: mobility_system_timer (ctx.timestamp) Fri Dec 19 2025 08:19:29 GMT-0600 () - (timer.last_timestamp) Fri Dec 19 2025 08:19:20 GMT-0600 () = +9.410461
This happens consistently when the module starts up. Although its rare, I have also seen some negative times as well.
Are there any hooks for module startup to do some cleaning such as recalculate my last_timestamp?