In your IScheduledTaskHandler, you have to implement Process to provide your task implementation (I Advise you to put your implementation in another service class), and you have to register your task in the task manager. Once in the Handler constructor to register the first task, and then in the process implementation, to ensure that once a task was executed, the next one is scheduled.
Here is a sample:
public class MyTaskHandler : IScheduledTaskHandler
{
private const string TaskType = "MyTaskUniqueID";
private readonly IScheduledTaskManager _taskManager;
public ILogger Logger { get; set; }
public MyTaskHandler(IScheduledTaskManager taskManager)
{
_taskManager = taskManager;
Logger = NullLogger.Instance;
try
{
DateTime firstDate = //Set your first task date (utc).
ScheduleNextTask(firstDate);
}
catch(Exception e)
{
this.Logger.Error(e,e.Message);
}
}
public void Process(ScheduledTaskContext context)
{
if (context.Task.TaskType == TaskType)
{
try
{
//Do work (calling an IService for instance)
}
catch (Exception e)
{
this.Logger.Error(e, e.Message);
}
finally
{
DateTime nextTaskDate = //Your next date (utc).
this.ScheduleNextTask(nextTaskDate);
}
}
}
private void ScheduleNextTask(DateTime date)
{
if (date > DateTime.UtcNow )
{
var tasks = this._taskManager.GetTasks(TaskType);
if (tasks == null || tasks.Count() == 0)
this._taskManager.CreateTask(TaskType, date, null);
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…