Skip to content

Instantly share code, notes, and snippets.

@michlimlim
Created March 19, 2023 19:21
Show Gist options
  • Save michlimlim/b2ca54a281264067911ca1d6c6501c50 to your computer and use it in GitHub Desktop.
Save michlimlim/b2ca54a281264067911ca1d6c6501c50 to your computer and use it in GitHub Desktop.
Track time spent in app: network-efficient case: App Active events
/// App singleton responsible for scheduling periodic background tasks for sending batches of
/// telemetry events.
pub struct TelemetryCollector {
server_api: Arc<ServerApi>,
}
impl TelemetryCollector {
pub fn new(server_api: Arc<ServerApi>) -> Self {
Self { server_api }
}
/// Schedules a background task to send an active usage event in a segment request if
/// telemetry is enabled. The scheduled task once again schedules itself after
/// `ACTIVE_USAGE_DURATION`.
fn schedule_send_active_usage_event(&self, ctx: &mut ModelContext<TelemetryCollector>) {
let server_api = self.server_api.clone();
let _ = ctx.spawn(
async move {
// Record app active if there was any activity now or right after the previous check
let last_active_timestamp = App::last_active_timestamp();
if last_active_timestamp + ACTIVE_USAGE_DURATION.as_secs() as i64
> Utc::now().timestamp()
{
if let LocalResult::Single(timestamp) =
Utc.timestamp_opt(last_active_timestamp, 0)
{
ui::telemetry::record_app_active_event(
server_api.user_id(),
server_api.anonymous_id(),
timestamp,
);
}
}
Timer::after(ACTIVE_USAGE_DURATION).await;
},
|me, _, ctx| me.schedule_send_active_usage_event(ctx),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment