Job
直接贴代码:
public interface ICronJob {
// 线程运行 void Run(DateTime dateTime);
// 线程终止 void Abort(); }
public class CronJobBase : ICronJob { private readonly object _object = new object(); private Thread _thread; private DateTime _runTime = DateTime.Now; private int _span = 3;//时间间隔 3s public CronJobBase() { } public CronJobBase(int span) { _span = span; } public void Run(DateTime dateTime) { if (_thread != null && _thread.ThreadState == ThreadState.Running) return; if (_runTime.AddSeconds(_span) > dateTime) return; _runTime = dateTime; _thread = new Thread(ExecuteHandler); _thread.Start(); } public void Abort() { _thread.Abort(); } private void ExecuteHandler() { try { Execute(); } catch (Exception ex) { throw new Exception(ex.ToString()); } } protected virtual void Execute() { } }
public class Job : CronJobBase { private int _span = 0; public Job() { } public Job(int span) : base(span) { this._span = span; } protected override void Execute() { if (_span == 0) Console.WriteLine("我是Job,我使用默认时间执行!" + DateTime.Now.ToString("s")); else Console.WriteLine("我是Job,我间隔{0}s执行!{1}", _span, DateTime.Now.ToString("s")); } }
public interface ICronMon { void AddJob(ICronJob job); void Start(); void Stop(); }
public class CronMon : ICronMon { private readonly System.Timers.Timer _timer = new System.Timers.Timer(1000); private readonly List<ICronJob> _jobs = new List<ICronJob>(); private DateTime _last = DateTime.Now; public CronMon() { _timer.AutoReset = true; _timer.Elapsed += _timer_Elapsed; } private void _timer_Elapsed(object sender, ElapsedEventArgs e) { if (DateTime.Now.Second != _last.Second) { _last = DateTime.Now; foreach (var item in _jobs) { item.Run(DateTime.Now); } } } public void AddJob(ICronJob job) { _jobs.Add(job); } public void Start() { _timer.Start(); } public void Stop() { _timer.Stop(); foreach (var item in _jobs) { item.Abort(); } } }
控制台调用
class Program { private static readonly CronMon CronMon = new CronMon(); static void Main(string[] args) { Start(); Console.ReadKey(); } public static void Start() { CronMon.AddJob(new Job()); CronMon.AddJob(new Job(10)); CronMon.AddJob(new Job(5)); CronMon.Start(); } }
运行效果如下: