public ScheduleJob AddJob(ScheduleTask task, DateTime executionTime, bool doRepeat, int? repeatPeriod, bool tryRecover)
        {
            _log.Write("Добавление нового таска " + task.Name);
            ScheduleJob newJob = new ScheduleJob
                                     {
                                         CreationDate = DateTime.Now,
                                         ExecutionDate = DateTime.Now,
                                         NextExecutionDate = executionTime,
                                         Task = task.Serialize(),
                                         State = (byte)JobState.ReadyToStart,
                                         RepeatPeriod = repeatPeriod,
                                         DoRepeat = doRepeat,
                                         TryRecover = tryRecover,
                                         IsUnique = task.IsUnique,
                                         Title = task.Name,
                                         Type = task.GetType().FullName
                                     };

            if (newJob.IsUnique)
            {
                var oldjob = DataService.PerThread.ScheduleJobSet.FirstOrDefault(x => x.Type == newJob.Type && (x.State == (byte)JobState.ReadyToStart || x.State == (byte)JobState.ReadyToRecover || x.State == (byte)JobState.Started));
                if (oldjob != null)
                {
                    if (oldjob.State == (byte)JobState.Started)
                    {
                    }
                    else
                    {
                        oldjob.RepeatPeriod = newJob.RepeatPeriod;
                        oldjob.DoRepeat = newJob.DoRepeat;
                        oldjob.TryRecover = newJob.TryRecover;
                        oldjob.Title = newJob.Title;
                        DataService.PerThread.SaveChanges();
                    }

                    return oldjob;
                }
            }

            SaveJobsToDb(newJob);
            return newJob;
        }
        private void FixupScheduleJob(ScheduleJob previousValue)
        {
            if (previousValue != null && previousValue.ScheduleExecutionInfo.Contains(this))
            {
                previousValue.ScheduleExecutionInfo.Remove(this);
            }

            if (ScheduleJob != null)
            {
                if (!ScheduleJob.ScheduleExecutionInfo.Contains(this))
                {
                    ScheduleJob.ScheduleExecutionInfo.Add(this);
                }
                if (ScheduleJobId != ScheduleJob.Id)
                {
                    ScheduleJobId = ScheduleJob.Id;
                }
            }
        }
        private void Scheduling()
        {
            while (true)
            {
                _log.Write("Начало основного цикла");
                if (_nextJob != null)
                {
                    _log.Write("У меня есть назначенная задача id " + _nextJob.Id);
                    //Смотрим настало ли время для выполнения таска
                    if ((_nextJob.NextExecutionDate - DateTime.Now).TotalMilliseconds < _accuracyMilliseconds)
                    {
                        ExecuteJob(_nextJob);
                        _nextJob = null;
                    }
                    else
                    {
                        Thread.Sleep((int)((_nextJob.NextExecutionDate - DateTime.Now).TotalMilliseconds)+1);
                    }
                }

                //проверяем не пуст ли список предстоящих работ
                if (_queue.Count == 0)
                {
                    var newJobs = GetIncomingJobs();
                    foreach (var job in newJobs)
                    {
                        _queue.Enqueue(job);
                    }
                }

                //Получаем следующую работу
                if (_queue.Count != 0)
                {
                    _queue.TryDequeue(out _nextJob);
                }
                else
                {
                    //Расчет времени сна
                    int sleepingTime = (int)(_callPeriodicitySeconds);
                    if (_nextJob != null && (_nextJob.NextExecutionDate - DateTime.Now).TotalSeconds < _callPeriodicitySeconds)
                    {
                        sleepingTime = (int)((_nextJob.NextExecutionDate - DateTime.Now).TotalSeconds);
                    }

                    if (sleepingTime > 0)
                    {
                        _nextWakeupTime = DateTime.Now.AddSeconds(sleepingTime);
                        Thread.Sleep((sleepingTime * 1000));
                    }
                }
            }
        }
 private void ExecuteJob(ScheduleJob executeJob)
 {
     _log.Write("Приступаю к выполнению джобы id: " + executeJob.Id);
     ScheduleTask executeTask = ScheduleService.Deserialize(executeJob.Task);
     Action execute = executeTask.Execute;
     executeJob.ExecutionDate = DateTime.Now;
     executeJob.State = (byte)JobState.Started;
     SaveJobStatusToDb(executeJob);
     Tuple<Guid, Action, DateTime> args = new Tuple<Guid, Action, DateTime>(executeJob.Id, execute, DateTime.Now);
     execute.BeginInvoke(JobIsDone, args);
 }
 private static void SaveJobsToDb(ScheduleJob job)
 {
     DataService.PerThread.ScheduleJobSet.AddObject(job);
     DataService.PerThread.SaveChanges();
 }
        //отвратительно
        private static void SaveJobStatusToDb(ScheduleJob job)
        {
            var jobFromDb = DataService.PerThread.ScheduleJobSet.FirstOrDefault(x => x.Id == job.Id);
            jobFromDb.State = job.State;
            jobFromDb.ExecutionDate = job.ExecutionDate;

            DataService.PerThread.SaveChanges();
        }
 private static void Log(ScheduleJob scheduleJob, DateTime startDate, DateTime endDate, string info, ScheduleTaskState state)
 {
     ScheduleExecutionInfo log = new ScheduleExecutionInfo()
     {
         StartDate = startDate,
         EndDate = endDate,
         ScheduleJobId = scheduleJob.Id,
         Info = info,
         State = (byte)state
     };
     DataService.PerThread.ScheduleExecutionInfoSet.AddObject(log);
     DataService.PerThread.SaveChanges();
 }
 private static void SaveJobsToDb(ScheduleJob job)
 {
     DataService.PerThread.ScheduleJobSet.AddObject(job);
     DataService.PerThread.SaveChanges();
 }