使用Orchard CMS安排的任务 [英] Scheduled tasks using Orchard CMS
问题描述
我需要使用Orchard CMS创建计划任务.
I need to create a scheduled task using Orchard CMS.
我有一种服务方法(例如,它从外部来源加载一些数据),我需要每天8:00 AM执行一次.
I have a service method (let's say it loads some data from external sources), and I need to execute it every day at 8:00 AM.
我发现必须使用IScheduledTaskHandler和IScheduledTaskManager ...有人知道如何解决此问题吗?一些示例代码将不胜感激.
I figured out I have to use IScheduledTaskHandler and IScheduledTaskManager... Does anyone know how to solve this problem? Some sample code will be appreciated.
推荐答案
在您的IScheduledTaskHandler中,您必须实现Process以提供您的任务实现(我建议您将实现放在另一个服务类中),并且必须注册您在任务管理器中的任务.一旦在Handler构造函数中注册了第一个任务,然后在流程实现中,以确保一旦任务执行完毕,就计划下一个任务.
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.
以下是示例:
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);
}
}
}
这篇关于使用Orchard CMS安排的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!