使用Orchard CMS的计划任务

时间:2012-01-18 19:31:11

标签: model-view-controller orchardcms

我需要使用Orchard CMS创建计划任务。

我有一个服务方法(假设它从外部源加载一些数据),我需要每天早上8点执行它。

我想我必须使用IScheduledTaskHandler和IScheduledTaskManager ......有谁知道如何解决这个问题?一些示例代码将被评估。

2 个答案:

答案 0 :(得分:11)

在您的IScheduledTaskHandler中,您必须实现Process以提供您的任务实现(我建议您将您的实现放在另一个服务类中),并且您必须在任务管理器中注册您的任务。一旦在Handler构造函数中注册第一个任务,然后在流程实现中,确保一旦执行任务,就会安排下一个任务。

以下是一个示例:

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);
      }
  }


}

答案 1 :(得分:2)

您应该使用@Entity @Table(name = "system_configuration_metadata") public class SysConfigMetaDataDTO { @Id @Column(name = "id") private Long id; @Column(name = "system_configuration_id") private Long systemConfigurationId; } 的实现进行第一次调度,而不是在任务构造函数中进行调度,以避免添加多个任务。

这里是一个抽象的address=/example.com/0.0.0.0类,您可以实现:

用法

public class NeutralFactory: NPCFactory
    {
        private List<Func<int, Creature>> humanoids = new List<Func<int, Creature>> {
            hp=> new Dwarf(hp),
            hp=> new Fairy(hp),
            hp=> new Elf(hp),
            hp=> new Troll(hp),
            hp=> new Orc(hp)
        };
        private Random random = new Random();

        public Creature CreateHumanoid(int hp = 100)
        {
            int index = random.Next(humanoids.Count);
            return humanoids[index](hp);
        }
    }

抽象的日常任务处理程序和调度程序

IOrchardShellEvents

通过在任务处理程序类上使用schedule方法和DailyTaskHandler实现,可以避免使用任务计划程序类。

相关问题