在Drupal 7中设置Cron作业

时间:2018-08-06 19:19:15

标签: drupal cron drupal-7

我对drupal还是很陌生,并被要求设置一个每小时运行一次的cron作业。我有一个php文件,该文件会生成一个将在其他站点上使用的xml文件。

我的问题是:是否将mycron.php放入根目录(与cron.php相同)并配置crontabs使其每小时运行mycron.php?

任何指导表示赞赏。

2 个答案:

答案 0 :(得分:1)

您可以在自定义模块中使用hook_cron()编写自己的cron作业,并使用贡献的模块Elysia Cron [https://www.drupal.org/project/elysia_cron]对其进行设置,以获取每个cron任务的时间和频率。

答案 1 :(得分:1)

最初,我以类似的问题来到此页面。这基本上是我发现的。

您不从PHP代码运行cron作业,而是从服务器操作系统运行cron作业。 Cron作业只能在Linux,Unix或macOS中设置,而Windows并未预装cron系统。

如果使用VPS,则可以从操作系统(例如ubuntu)设置cron作业。或者,如果您使用共享主机,则最有可能能够从帐户的管理菜单中设置cron作业,这取决于您的主机提供商。

您要做的是在Drupal模块hook_menu中创建一个端点。菜单中的端点应该链接到回调函数,该函数将执行您要定期运行的操作。

function module_name_menu() {
  return [
    'path/to/endpoint/%' => [
      'title'            => t(Menu title), 
      'description'      => 'Some description',
      'page callback'    => 'name_of_function_to_call',
      // Optional argument passed to the callback function, number relates to the position in the path
      'page arguments'   => [3], 
      'access arguments' => ['type of access'],
      'type'             => MENU_CALLBACK,
    ]
  ];
}

检查hook_menu链接以查看函数返回数组中的元素的作用。

/**
 * Cron job callback function
 * @param string $param Parameter sent through the url
 */
function name_of_function_to_call($param) {
  // Do something with the param and perform some tasks
}

在cron作业中,您将需要进行设置,将cron作业指向端点位置。下例中的cron作业将在1月的每个第一天和1月的每个星期一的4点一分钟开始运行(分钟,小时,每月的某天,月份,一周的某天):

01 04 1 1 1 wget -O - -q -t 1 http://siteurl.tld/path/to/endpoint/argument

(例如Drupal documentation的示例,请执行man wget来找出wget选项的作用)

编辑:您显然也有hook_cron选项。您将代码放在..._cron() {}函数中的位置,该函数将在运行页面范围的cron作业时运行,但这并没有太多的控制权。