using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Collections.ObjectModel; using sharpknife.Commands; using sharpknife.Data; namespace sharpknife.Engines { class SchedulerEngine { public enum StatusCode { Stopped, Running, Paused } public StatusCode Status { get; set; } private Thread thread; private static SchedulerEngine engine; public static SchedulerEngine GetEngine() { if (engine == null) engine = new SchedulerEngine(); return engine; } public ObservableCollection Commands { get; set; } private SchedulerEngine() { Commands = new ObservableCollection(); Status = StatusCode.Stopped; using (databaseEntities context = new databaseEntities()) { var query = (from c in context.ScheduledCommand select c); foreach (ScheduledCommand command in query) { Commands.Add(command); } } } private void Engine() { string machineName = Environment.MachineName.ToLowerInvariant(); Thread.Sleep(5000); while (Status == StatusCode.Running || Status == StatusCode.Paused) { if (Status == StatusCode.Running) { var query = (from c in Commands where c.Status == ScheduledCommand.StatusCodes.Enabled && (c.NextExecution <= DateTime.Now || c.NextExecution == null) && (c.AllowedHost == "*" || c.AllowedHost.ToLowerInvariant() == machineName) select c); foreach (ScheduledCommand command in query) { if (command != null) { try { Command batchCommand = null; if (!string.IsNullOrEmpty(command.CommandParameters)) { batchCommand = ScheduledCommand.CreateCommand(command.CommandName, new object[] { command.CommandParameters }); } else { batchCommand = ScheduledCommand.CreateCommand(command.CommandName); } if (!command.FirstExecuted.HasValue) command.FirstExecuted = DateTime.Now; command.LastExecuted = DateTime.Now; command.NextExecution = command.SchedulationRule.CalculateNextRun(command.LastExecuted.HasValue ? command.LastExecuted.Value : DateTime.Now); command.Save(); CommandEngine.GetEngine().Commands.Add(batchCommand); } catch (Exception ex) { LogItem item = new LogItem(ex.ToString()); item.Save(); } } } } Thread.Sleep(1000); } } public void Start() { Status = StatusCode.Running; thread = new Thread(Engine); thread.SetApartmentState(ApartmentState.STA); thread.Start(); } public void Pause() { if (Status == StatusCode.Running) { Status = StatusCode.Paused; } } public void Resume() { if (Status == StatusCode.Paused) { Status = StatusCode.Running; } } public void Stop() { Status = StatusCode.Stopped; thread.Join(5000); thread.Abort(); } public void Dispose() { Stop(); } } }