//
// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
// █__ --█ █__ --█ ◄█ - █
// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
// │ Copyright (c) JP Dillingham.
// │
// │ This program is free software: you can redistribute it and/or modify
// │ it under the terms of the GNU Affero General Public License as published
// │ by the Free Software Foundation, version 3.
// │
// │ This program is distributed in the hope that it will be useful,
// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// │ GNU Affero General Public License for more details.
// │
// │ You should have received a copy of the GNU Affero General Public License
// │ along with this program. If not, see https://www.gnu.org/licenses/.
// │
// │ This program is distributed with Additional Terms pursuant to Section 7
// │ of the AGPLv3. See the LICENSE file in the root directory of this
// │ project for the complete terms and conditions.
// │
// │ https://slskd.org
// │
// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
// │ SPDX-FileCopyrightText: JP Dillingham
// │ SPDX-License-Identifier: AGPL-3.0-only
// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
//
using System;
using System.Timers;
namespace slskd
{
///
/// A counter that counts up over a set time period.
///
public class TimedCounter : IDisposable
{
///
/// Initializes a new instance of the class.
///
/// The interval at which the OnElapsed delegate is called and the count resets.
/// The delagate to invoke with the current count when the timer elapses.
public TimedCounter(TimeSpan interval, Action onElapsed)
{
OnElapsed = onElapsed;
Timer = new Timer(interval);
Timer.Elapsed += Elapsed;
Timer.Start();
}
///
/// Gets the current count.
///
public long Count { get; private set; } = 0;
private Timer Timer { get; }
private Action OnElapsed { get; }
private bool Disposed { get; set; }
///
/// Counts up by the specified .
///
/// The number to add to the count.
public void CountUp(long count = 1)
{
Count += count;
}
///
/// Disposes this instance.
///
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!Disposed)
{
if (disposing)
{
Timer.Dispose();
}
Disposed = true;
}
}
private void Elapsed(object sender, ElapsedEventArgs args)
{
var count = Count;
Count = 0;
OnElapsed?.Invoke(count);
}
}
}