private void TaskLifeCycle()
{
try
{
// Create task object.
Type taskType = Type.GetType(this.ConfigurationElement.Task);
DebtLogic.Service.BackgroundTask bgTask = Activator.CreateInstance(taskType) as BackgroundTask;
bgTask.Context = this;
FireEvent(CreatedEventKey, new BackgroundTaskEventArgs(bgTask));
FireEvent(InitilizingEventKey, new BackgroundTaskEventArgs(bgTask));
bgTask.Initilize();
FireEvent(InitilizedEventKey, new BackgroundTaskEventArgs(bgTask));
// while the thread is alive, and did not abort then run.
while (this.CurrentThread.IsAlive)
{
try
{
//can run then block
if (CanRun(bgTask))
{
Run(bgTask);
}
}
catch (ThreadAbortException)
{
return;
}
catch (Exception ex)
{
FireEvent(ErrorEventKey,new BackgroundTaskErrorArgs(ex) );
}
}
bgTask.Dispose();
}
catch (ThreadAbortException)
{
return;
}
catch (Exception ex)
{
FireEvent(ErrorEventKey, new BackgroundTaskErrorArgs(ex));
}
}
private bool CanRun(BackgroundTask bgTask)
{
if (this.ConfigurationElement.EventBasedTask)
{
return bgTask.CanRun();
}
TimeSpan time;
if (this.ConfigurationElement.Time != TimeSpan.Zero)
{
time = this.ConfigurationElement.Time - DateTime.Now.TimeOfDay;
if (time.TotalMilliseconds < 0)
time = time.Add(new TimeSpan(24, 0, 0));
}
else
{
time = new TimeSpan(0, 0, this.ConfigurationElement.Interval);
}
Thread.Sleep(time);
return bgTask.CanRun();
}