using System;
using System.Threading;
using VCommon.Logging;

namespace VCommon.Services
{
    public abstract class CycleService : IService
    {
        private Thread _thread;
        private bool _isRunning;

        protected int SecLoopInterval = 30;
        protected int MsWaitStop = 5000;

        private void CycleRun()
        {
            while (_isRunning)
            {
                try
                {
                    Run();
                }
                catch (Exception e)
                {
                    Logger.Error("Exception in CycleRun", e);
                }
                for (var i = 0; i < SecLoopInterval && _isRunning; i++) Thread.Sleep(1000);
            }
        }

        protected abstract void Run();

        public void Start()
        {
            _isRunning = true;
            _thread = new Thread(CycleRun) { Name = GetType().Name };
            _thread.Start();
        }

        public void Stop()
        {
            _isRunning = false;
            _thread.Join(MsWaitStop);
            _thread.Abort();
        }
    }
}
