使用 Orchard CMS 的计划任务 [英] Scheduled tasks using Orchard CMS

查看:19
本文介绍了使用 Orchard CMS 的计划任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to create a scheduled task using Orchard CMS.

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆