Skip to content

Inactivity Tracking

MrCakeSlayer edited this page Sep 24, 2022 · 1 revision

Lavalink4NET provides a way to disconnect to unused / inactive players that use resources, but nobody is listening.

For example, you can stop unused / inactive players when:

  • Nobody in the channel is listening.
  • No track is playing.

Setting up the service

First you need to create an instance of the InactivityTrackingService:

"Native" way

using Lavalink4NET.Tracking;

// initialize service instance with default options
var service = new InactivityTrackingService(
    audioService, // The instance of the IAudioService (e.g. LavalinkNode)
    clientWrapper, // The discord client wrapper instance
    new InactivityTrackingOptions());

// Start tracking inactive players
service.BeginTracking();

Using Dependency Injection / IoC

using Lavalink4NET.Tracking;

// initialize DI service provider
var serviceProvider =
    [...]
    .AddSingleton<InactivityTrackingOptions>()
    .AddSingleton<InactivityTrackingService>()
    .BuildServiceProvider();

// get service and begin player tracker
serviceProvider.GetRequiredService<InactivityTrackingService>()
    .BeginTracking();

Constructor Parameters

Name Description
audioService The underlying audio service to track the players.
clientWrapper The discord client wrapper, same as in audioService.
options Additional options, see below.
logger The logger for logging trackings.

Optional options

You can also change the behavior of the InactivityTrackingService to your needs using the InactivityTrackingOptions specified in the constructor:

Poll interval

The poll interval is the interval the service checks for inactive / unused players, the default 5 seconds.

Disconnect delay

The disconnect delay is the delay the player should stop after it has been marked as inactive / unused. The default disconnect delay is 30 seconds, after this time the player will stop if it has been tracked as inactive. You can use TimeSpan.Zero to disable this and let the player disconnect after tracking directly.

Track inactivity

The track inactivity property starts tracking the players after initializing the instance of the InactivityTrackingService. The default value is false. This can be useful when not using Dependency Injection or IoC.

Delay First Track

This property adds a delay to the first poll if enabled. The delay is the same as specified in PollInterval.

Example Options

var options = new InactivityTrackingOptions {
    // Disconnect the player after 10 seconds if it inactive.
    DisconnectDelay = TimeSpan.FromSeconds(10),

    // Check every 4 seconds for an inactive player.
    PollInterval = TimeSpan.FromSeconds(4),

    // Start Tracking after calling the constructor.
    TrackInactivity = true
};

new InactivityTrackingService(options);

Here is an example for the options.

This will let the tracking service disconnect players that are inactive since 10 seconds, checking every 4 seconds after instantiation.