通过 Web 套接字向客户端发送消息。每条消息有不同的时间间隔

Sending messages to client over Web socket. Each message has different time interval

我正在开发 server/client 应用程序。服务器按时间间隔向客户端推送消息。每条消息可以有不同的时间属性。

处理此问题的最佳方法是什么?我可以暂停线程,但这似乎有点老套。这种情况是否有最佳实践?

您可以使用 Quartz.NET.

根据你的标签,我想你正在使用 C#,所以你可以看到 Microsoft doc 关于任务 Class(这实现了线程)

假设你想使用 SignalR(你添加了一个标签),一个简单的计时器就可以完成这项工作:

public sealed class MatchingSupervisor
{
    private static readonly ILog Log = LogManager.GetLogger(typeof(MatchingSupervisor));
    private readonly IHubContext _hub;
    private readonly Timer _timer;

    #region Singleton

    public static MatchingSupervisor Instance => SupervisorInstance.Value;

    // Lazy initialization to ensure SupervisorInstance creation is threadsafe
    private static readonly Lazy<MatchingSupervisor> SupervisorInstance = new Lazy<MatchingSupervisor>(() => 
            new MatchingSupervisor(GlobalHost.ConnectionManager.GetHubContext<YourHubClass>()));

    private MatchingSupervisor(IHubContext hubContext)
    {
        _hub = hubContext;
        _timer = new Timer(Run, null, 0, Timeout.Infinite);
    }

    #endregion

    private async void Run(object state)
    {
        // TODO send messages to clients

        // you can use _timer.Change(newInterval, newInterval) here 
        // if you need to change the next interval
        var newInterval = TimeSpan.FromSeconds(60);
         _timer.Change(newInterval, newInterval);
    }
}

为确保您的计时器在系统或应用程序重新启动(系统关闭、应用程序回收等)时重新启动,您应该在 Owin Startup class:

上获取一个实例
public class Startup
{
    private MatchingSupervisor _conversationManager;

    public void Configuration(IAppBuilder app)
    {
        // TODO app configuration

        // Ensure supervisor starts
        _supervisor = MatchingSupervisor.Instance;
    }
}