using RFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;

namespace jiouosdptask
{
    public class TaskTimer : IDisposable
    {
        Timer timer;
        bool IsHander = false;
        /// <summary>
        /// 是否允许上一次任务还未执行完,可以继续执行相同的任务
        /// </summary>
        public bool IsRepeatedly = false;
        public string Name { get; set; }
        Action<Timer> action;
        /// <summary>
        /// 定时执行
        /// </summary>
        /// <param name="name">任务名称</param>
        /// <param name="interval">间隔(毫秒)</param>
        /// <param name="action">执行的方法</param>
        public TaskTimer(string name, int interval, Action<Timer> action)
            : this(name, interval, false, action)
        {

        }
        /// <summary>
        /// 定时执行
        /// </summary>
        /// <param name="name">任务名称</param>
        /// <param name="interval">间隔(毫秒)</param>
        /// <param name="interval">是否允许上一次任务还未执行完,可以继续执行相同的任务</param>
        /// <param name="action">执行的方法</param>
        public TaskTimer(string name, int interval, bool isRepeatedly, Action<Timer> action)
        {
            this.IsRepeatedly = isRepeatedly;
            this.Name = name;
            this.action = action;
            timer = new Timer();
            timer.Interval = interval;
            timer.Elapsed += timer_Elapsed;
            timer.Start();
        }

        private void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                timer.Stop();
                Log.Write("开始执行{0}", Name);
                action(timer);
            }
            catch (Exception ex)
            {
                Log.Write("执行{0}出错了,异常:{1}", Name, ex.Message);
            }
            finally
            {
                Log.Write("执行完{0}",Name);
                timer.Start();
            }
        }

        public void Dispose()
        {
            if (timer != null) timer.Dispose();
        }
    }
}
