/*
Kooboo is a content management system based on ASP.NET MVC framework. Copyright 2009 Yardi Technology Limited.
This program is free software: you can redistribute it and/or modify it under the terms of the
GNU General Public License version 3 as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see http://www.kooboo.com/gpl3/.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Everest.Library;
namespace Everest.Library.Scheduler{
public class Scheduler : IDisposable
{
/// <summary>
///
/// </summary>
public volatile static Scheduler Instance = new Scheduler();
private volatile static object schedulerLocker = new object();
private bool started = false;
private Dictionary<string, JobExecutor> jobs = new Dictionary<string, JobExecutor>();
protected Scheduler() { }
/// <summary>
/// Starts this jobs.
/// </summary>
public void Start()
{
if (started == false)
{
lock (schedulerLocker)
{
if (started == false)
{
IScheduleProvider scheduleProvider = UnityManager.Resolve<IScheduleProvider>();
foreach (var item in scheduleProvider.GetSchedules(true))
{
AddJob(item);
}
started = true;
}
}
}
}
/// <summary>
/// Refreshes this job.
/// </summary>
public void Refresh()
{
lock (schedulerLocker)
{
IScheduleProvider scheduleProvider = UnityManager.Resolve<IScheduleProvider>();
IEnumerable<Schedule> refreshedSchedule = scheduleProvider.GetSchedules(false);
List<string> removedJob = new List<string>();
//delete the removed jobs..
foreach (var job in jobs)
{
if (refreshedSchedule.Where(s => s.Key == job.Key).Count() == 0)
{
Log.Info(string.Format(Resources.JobRemoved, job.Key, DateTime.Now));
job.Value.Stop();
removedJob.Add(job.Key);
}
}
foreach (var key in removedJob)
{
jobs.Remove(key);
}
//
foreach (var item in refreshedSchedule)
{
if (!jobs.ContainsKey(item.Key))
{
AddJob(item);
}
else if (item.Changed)
{
if (jobs.ContainsKey(item.Key))
{
//remove the old job
jobs[item.Key].Stop();
jobs.Remove(item.Key);
}
AddJob(item);
}
}
}
}
private void AddJob(Schedule item)
{
Log.Info(string.Format(Resources.JobAdded, item.Key, DateTime.Now));
JobExecutor executor = new JobExecutor(item.Key, item.JobType, item.Interval, item.Parameter);
executor.Run();
jobs.Add(item.Key, executor);
}
/// <summary>
/// Stops this instance.
/// </summary>
public void Stop()
{
if (started != false)
{
lock (schedulerLocker)
{
if (started != false)
{
while (jobs.Count > 0)
{
var item = jobs.First();
item.Value.Stop();
jobs.Remove(item.Key);
}
}
started = false;
}
}
}
#region IDisposable Members
public void Dispose()
{
if (started)
{
Stop();
}
}
#endregion
}
}
|