Skip to content

Instantly share code, notes, and snippets.

@verborghs
Created October 29, 2019 13:48
Show Gist options
  • Save verborghs/ce9aac66ccf0213e8b70d14a081ca045 to your computer and use it in GitHub Desktop.
Save verborghs/ce9aac66ccf0213e8b70d14a081ca045 to your computer and use it in GitHub Desktop.
Timed Queue with interface as callback
using System.Collections.Generic;
using System.Diagnostics;
namespace Utils
{
public interface TimedQueueCallback
{
void OnMessage(string message);
void OnEmpty();
}
public class TimedQueue
{
private float _dequeueTimer;
private readonly float _dequeueDelay;
private float _emptyTimer;
private readonly float _emptyDelay;
private readonly Queue<string> _messageQueue = new Queue<string>();
private TimedQueueCallback _callback;
public TimedQueue(TimedQueueCallback callback, float dequeueDelay = 0.5f, float emptyDelay = 2.0f)
{
_callback = callback;
_dequeueDelay = dequeueDelay;
_dequeueTimer = dequeueDelay + 0.1f;
_emptyDelay = emptyDelay;
_emptyTimer = _emptyDelay + 0.1f;
}
public void Update(float deltaTime)
{
if (_messageQueue.Count > 0)
{
_emptyTimer = 0;
if (_dequeueTimer > _dequeueDelay)
{
_callback.OnMessage(_messageQueue.Dequeue());
_dequeueTimer = 0;
}
_dequeueTimer += deltaTime;
}
else
{
if (_emptyTimer < _emptyDelay)
{
_emptyTimer += deltaTime;
if (_emptyTimer > _emptyDelay)
{
_callback.OnEmpty();
}
}
}
}
public void Enqueue(string t)
{
_messageQueue.Enqueue(t);
_emptyTimer = 0.0f;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment