在后台监控任务

时间:2018-05-01 16:01:19

标签: c# asynchronous timer task background-process

我正在寻找创建代码,我的所有Windows服务都会使用这些代码向数据库表写一个“心跳”,以便我创建一个montior应用程序,以提高对服务何时启动的认识。

为此,我创建了一个ServiceHeartbeat项目,其中包含一个类Heartbeat,用于在数据库中查找我的服务记录,并添加了一个计时器,每分钟执行一次,如下所示:

/// <summary>
/// Class to perform the registering of a services' "heartbeat"
/// </summary>
public class Heartbeat
{
    private readonly string _serviceName;
    private IService _service;
    private readonly IServiceRepository _serviceRepository;
    private readonly Timer _timer = new Timer();
    private bool continueBeating = true;

    /// <summary>
    /// Constructor
    /// </summary>
    public Heartbeat(string serviceName)
        :this(new ServiceRepository(new ConnectionFactory()))
    {
        _serviceName = serviceName;
    }

    internal Heartbeat(IServiceRepository serviceRepository)
    {
        _serviceRepository = serviceRepository;
    }


    public async Task<IService> GetSvc(string serviceName)
    {
        var svc = await _serviceRepository.FindByServiceNameAsync(_serviceName);

        return svc;
    }

    /// <summary>
    /// Begin inserting heartbeat record into monitor database
    /// </summary>
    public void Start()
    {
        try
        {
            _service = _serviceRepository.FindByServiceNameAsync(_serviceName).Result;
            if (_service != null)
            {
                _timer.Interval = _service.HeartbeatIntervalMins * 60 * 1000;
                _timer.Enabled = true;
                _timer.AutoReset = true;
                _timer.Elapsed += (sender, args) =>
                {
                    RegisterHeartbeat();
                };
                _timer.Start();
                while (continueBeating)
                {

                }
            }
        }
        catch (Exception ex)
        {
            _timer.Dispose();
        }
    }

    /// <summary>
    /// Stop registering service heartbeat in monitor database
    /// </summary>
    public void Stop()
    {
        continueBeating = false;
        _timer?.Dispose();
    }

    private void RegisterHeartbeat()
    {
        _serviceRepository.RegisterHeartbeat(_service.Id);
    }
}

这是更新我感兴趣的记录但是由于我的while(continueBeating)语句我阻塞线程所以任何新闻我的Heartbeat类并调用Start()的服务都不会继续使用它自己的功能作为我的开始永远不会回来。

如何让我的心跳类在后台启动和运行,反复进行,直到服务出现故障/停止为止,同时在我的服务中消耗代码继续执行?

0 个答案:

没有答案