簡體   English   中英

每秒打印消息數

[英]Print Number of Message per Second

我有一個無限循環。 我想每秒打印一條消息數。 它應該每秒打印一次消息計數。 例如,如果我在 1 秒內有 500 條消息,那么它應該在消息之后將計數打印為 500,然后如果在接下來的 1 秒內為 500,那么它應該在消息之后再次打印 500 這是我的代碼:

static void SimulatePublish()
{
  var counter = 1;
  while (true)
  {
    counter++;
    var testMessage = new MqttApplicationMessageBuilder()
      .WithTopic("MqttData")
      .WithPayload($"Payload: This is my Code")
      .WithAtMostOnceQoS()
      .WithRetainFlag()
      .Build();
    if (_client.IsConnected)
    {
      Console.WriteLine($"publishing at {DateTime.UtcNow}");
      _client.PublishAsync(testMessage);
    }
  }
}
int messagesDiff = 0;
long startTime = DateTimeOffset.Now.ToUnixTimeSeconds(), timeDiff;

TimerCallback printingLambda = (o) =>
{
    timeDiff = DateTimeOffset.Now.ToUnixTimeSeconds() - startTime;
    Console.WriteLine("Messages per second: " + messagesDiff / (double)timeDiff);
    startTime = DateTimeOffset.Now.ToUnixTimeSeconds();
    messagesDiff = 0;
};

Timer timer = new Timer(printingLambda, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));

while (true)
{
    //public message
    messagesDiff++;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM