Drupal 7 开发内部培训资料, 分头诗人

谁能给job_scheduler模块的简单例子

赞成!
0
否决!

我安装了这个模块,按说明试了下API,但是不知道为什么时灵时不灵的,麻烦使用过的大神给个例子学习学习。

1 个回答

赞成!
0
否决!

这里有个例子:Easily scheduling periodic tasks with Job Scheduler

weekly_task.module

/**
 * Compute statistics and record, this can take a long time!
 * 
 * This function should only be called once a week.
 */
function weekly_task_compute_statistics() {
  // Complicated code goes here
}

/**
 * Implements hook_cron_job_scheduler_info().
 */
function weekly_task_cron_job_scheduler_info() {
  $info = array();
  $info['weekly_task_statistics'] = array(
    'worker callback' => 'weekly_task_compute_statistics',
  );
  return $info;
}

/**
 * Implements hook_menu().
 */
function weekly_task_menu() {
  $items = array();

  $items['admin/config/system/weekly-task'] = array(
    'title' => 'Weekly task',
    'description' => 'Change options relating to the weekly task',
    'access arguments' => array('administer site configuration'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('weekly_task_admin_form'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

/**
 * Administration form for the weekly task.
 */
function weekly_task_admin_form($form, &$form_state) {
  $form['weekly_task_day'] = array(
    '#type' => 'select',
    '#title' => t('Day of the week'),
    '#description' => t('Choose the day of the week that the compute statistics function will run on.'),
    '#options' => array(0 => t('Sunday'), 1 => t('Monday'), 2 => t('Tuesday'), 3 => t('Wednesday'), 4 => t('Thursday'), 5 => t('Friday'), 6 => t('Saturday')),
    '#default_value' => variable_get('weekly_task_day', '0'),
  );

  $form = system_settings_form($form);

  $form['#submit'][] = 'weekly_task_admin_form_submit';

  return $form;
}

/**
 * Submit callback for Administration form.
 */
function weekly_task_admin_form_submit(&$form, &$form_state) {
  // The variables will have already been set by the time this callback runs.

  // Update the scheduled job.
  $job = array(
    'type' => 'weekly_stats',
    'period' => 86400 * 7,
    'crontab' => '0 0 * * ' . variable_get('weekly_task_day', 0),
    'periodic' => TRUE,
  );
  JobScheduler::get('weekly_task_statistics')->set($job);
}

weekly_task.install

/**
 * Implements hook_install().
 */
function weekly_task_install() {
  // Create a default scheduled job.
  $job = array(
    'type' => 'weekly_stats',
    'period' => 86400 * 7,
    'crontab' => '0 0 * * 0',
    'periodic' => TRUE,
  );
  JobScheduler::get('weekly_task_statistics')->set($job);
}