/**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $values = $form_state->getValues();
     $file = File::load($values['file'][0]);
     // Load File entity.
     $read_file = new \SplFileObject($file->url());
     // Create file handler.
     $lines = 1;
     $in_queue = 0;
     $queue = \Drupal::queue('eventninja');
     // Load queue
     while (!$read_file->eof()) {
         $data = $read_file->fgetcsv(';');
         if ($lines > 1) {
             // skip headers
             $user = user_load_by_mail($data[1]);
             if ($user === false) {
                 // Verify if user with specified email does not exist.
                 $queue->createItem($data);
                 $in_queue++;
             } else {
                 $this->logger('eventninja')->log(RfcLogLevel::NOTICE, 'User {mail} hasn\'t been created.', ['mail' => $data[1]]);
             }
         }
         $lines++;
     }
     if ($lines > 1) {
         drupal_set_message($this->t('@num records was scheduled for import', array('@num' => $in_queue)), 'success');
     } else {
         drupal_set_message($this->t('File contains only headers'), 'error');
     }
 }
Example #2
0
/**
 * Perform periodic actions.
 *
 * Modules that require some commands to be executed periodically can
 * implement hook_cron(). The engine will then call the hook whenever a cron
 * run happens, as defined by the administrator. Typical tasks managed by
 * hook_cron() are database maintenance, backups, recalculation of settings
 * or parameters, automated mailing, and retrieving remote data.
 *
 * Short-running or non-resource-intensive tasks can be executed directly in
 * the hook_cron() implementation.
 *
 * Long-running tasks and tasks that could time out, such as retrieving remote
 * data, sending email, and intensive file tasks, should use the queue API
 * instead of executing the tasks directly. To do this, first define one or
 * more queues via hook_queue_info(). Then, add items that need to be
 * processed to the defined queues.
 */
function hook_cron()
{
    // Short-running operation example, not using a queue:
    // Delete all expired records since the last cron run.
    $expires = \Drupal::state()->get('mymodule.cron_last_run', REQUEST_TIME);
    db_delete('mymodule_table')->condition('expires', $expires, '>=')->execute();
    \Drupal::state()->set('mymodule.cron_last_run', REQUEST_TIME);
    // Long-running operation example, leveraging a queue:
    // Fetch feeds from other sites.
    $result = db_query('SELECT * FROM {aggregator_feed} WHERE checked + refresh < :time AND refresh <> :never', array(':time' => REQUEST_TIME, ':never' => AGGREGATOR_CLEAR_NEVER));
    $queue = \Drupal::queue('aggregator_feeds');
    foreach ($result as $feed) {
        $queue->createItem($feed);
    }
}
Example #3
0
 /**
  * Tests that exactly one fetch task per project is created and not more.
  */
 function testFetchTasks()
 {
     $projecta = array('name' => 'aaa_update_test');
     $projectb = array('name' => 'bbb_update_test');
     $queue = \Drupal::queue('update_fetch_tasks');
     $this->assertEqual($queue->numberOfItems(), 0, 'Queue is empty');
     update_create_fetch_task($projecta);
     $this->assertEqual($queue->numberOfItems(), 1, 'Queue contains one item');
     update_create_fetch_task($projectb);
     $this->assertEqual($queue->numberOfItems(), 2, 'Queue contains two items');
     // Try to add project a again.
     update_create_fetch_task($projecta);
     $this->assertEqual($queue->numberOfItems(), 2, 'Queue still contains two items');
     // Clear storage and try again.
     update_storage_clear();
     update_create_fetch_task($projecta);
     $this->assertEqual($queue->numberOfItems(), 2, 'Queue contains two items');
 }
Example #4
0
/**
 * Perform periodic actions.
 *
 * Modules that require some commands to be executed periodically can
 * implement hook_cron(). The engine will then call the hook whenever a cron
 * run happens, as defined by the administrator. Typical tasks managed by
 * hook_cron() are database maintenance, backups, recalculation of settings
 * or parameters, automated mailing, and retrieving remote data.
 *
 * Short-running or non-resource-intensive tasks can be executed directly in
 * the hook_cron() implementation.
 *
 * Long-running tasks and tasks that could time out, such as retrieving remote
 * data, sending email, and intensive file tasks, should use the queue API
 * instead of executing the tasks directly. To do this, first define one or
 * more queues via a \Drupal\Core\Annotation\QueueWorker plugin. Then, add items
 * that need to be processed to the defined queues.
 */
function hook_cron()
{
    // Short-running operation example, not using a queue:
    // Delete all expired records since the last cron run.
    $expires = \Drupal::state()->get('mymodule.last_check', 0);
    \Drupal::database()->delete('mymodule_table')->condition('expires', $expires, '>=')->execute();
    \Drupal::state()->set('mymodule.last_check', REQUEST_TIME);
    // Long-running operation example, leveraging a queue:
    // Queue news feeds for updates once their refresh interval has elapsed.
    $queue = \Drupal::queue('aggregator_feeds');
    $ids = \Drupal::entityManager()->getStorage('aggregator_feed')->getFeedIdsToRefresh();
    foreach (Feed::loadMultiple($ids) as $feed) {
        if ($queue->createItem($feed)) {
            // Add timestamp to avoid queueing item more than once.
            $feed->setQueuedTime(REQUEST_TIME);
            $feed->save();
        }
    }
    $ids = \Drupal::entityQuery('aggregator_feed')->condition('queued', REQUEST_TIME - 3600 * 6, '<')->execute();
    if ($ids) {
        $feeds = Feed::loadMultiple($ids);
        foreach ($feeds as $feed) {
            $feed->setQueuedTime(0);
            $feed->save();
        }
    }
}
Example #5
0
 /**
  * {@inheritdoc}
  */
 public function getQueue() {
   return \Drupal::queue('scheduled_updates:' . $this->configuration['updater_type'],TRUE);
 }
Example #6
0
 /**
  * Tests interface translation update using cron.
  */
 public function testUpdateCron()
 {
     // Set a flag to let the locale_test module replace the project data with a
     // set of test projects.
     \Drupal::state()->set('locale.test_projects_alter', TRUE);
     // Setup local and remote translations files.
     $this->setTranslationFiles();
     $this->config('locale.settings')->set('translation.default_filename', '%project-%version.%language._po')->save();
     // Update translations using batch to ensure a clean test starting point.
     $this->drupalGet('admin/reports/translations/check');
     $this->drupalPostForm('admin/reports/translations', array(), t('Update translations'));
     // Store translation status for comparison.
     $initial_history = locale_translation_get_file_history();
     // Prepare for test: Simulate new translations being available.
     // Change the last updated timestamp of a translation file.
     $contrib_module_two_uri = 'public://local/contrib_module_two-8.x-2.0-beta4.de._po';
     touch(drupal_realpath($contrib_module_two_uri), REQUEST_TIME);
     // Prepare for test: Simulate that the file has not been checked for a long
     // time. Set the last_check timestamp to zero.
     $query = db_update('locale_file');
     $query->fields(array('last_checked' => 0));
     $query->condition('project', 'contrib_module_two');
     $query->condition('langcode', 'de');
     $query->execute();
     // Test: Disable cron update and verify that no tasks are added to the
     // queue.
     $edit = array('update_interval_days' => 0);
     $this->drupalPostForm('admin/config/regional/translate/settings', $edit, t('Save configuration'));
     // Execute locale cron tasks to add tasks to the queue.
     locale_cron();
     // Check whether no tasks are added to the queue.
     $queue = \Drupal::queue('locale_translation', TRUE);
     $this->assertEqual($queue->numberOfItems(), 0, 'Queue is empty');
     // Test: Enable cron update and check if update tasks are added to the
     // queue.
     // Set cron update to Weekly.
     $edit = array('update_interval_days' => 7);
     $this->drupalPostForm('admin/config/regional/translate/settings', $edit, t('Save configuration'));
     // Execute locale cron tasks to add tasks to the queue.
     locale_cron();
     // Check whether tasks are added to the queue.
     $queue = \Drupal::queue('locale_translation', TRUE);
     $this->assertEqual($queue->numberOfItems(), 3, 'Queue holds tasks for one project.');
     $item = $queue->claimItem();
     $queue->releaseItem($item);
     $this->assertEqual($item->data[1][0], 'contrib_module_two', 'Queue holds tasks for contrib module one.');
     // Test: Run cron for a second time and check if tasks are not added to
     // the queue twice.
     locale_cron();
     // Check whether no more tasks are added to the queue.
     $queue = \Drupal::queue('locale_translation', TRUE);
     $this->assertEqual($queue->numberOfItems(), 3, 'Queue holds tasks for one project.');
     // Ensure last checked is updated to a greater time than the initial value.
     sleep(1);
     // Test: Execute cron and check if tasks are executed correctly.
     // Run cron to process the tasks in the queue.
     $this->cronRun();
     drupal_static_reset('locale_translation_get_file_history');
     $history = locale_translation_get_file_history();
     $initial = $initial_history['contrib_module_two']['de'];
     $current = $history['contrib_module_two']['de'];
     $this->assertTrue($current->timestamp > $initial->timestamp, 'Timestamp is updated');
     $this->assertTrue($current->last_checked > $initial->last_checked, 'Last checked is updated');
 }
Example #7
0
 /**
  * Tests the queue() method.
  *
  * @covers ::queue
  */
 public function testQueue()
 {
     $queue = $this->getMockBuilder('Drupal\\Core\\Queue\\QueueFactory')->disableOriginalConstructor()->getMock();
     $queue->expects($this->once())->method('get')->with('test_queue', TRUE)->will($this->returnValue(TRUE));
     $this->setMockContainerService('queue', $queue);
     $this->assertNotNull(\Drupal::queue('test_queue', TRUE));
 }
Example #8
0
 /**
  * {@inheritdoc}
  *
  * @return \Drupal\Core\Queue\QueueInterface
  */
 public function getQueue($name)
 {
     return \Drupal::queue($name);
 }
Example #9
0
 /**
  * {@inheritdoc}
  */
 public static function postDelete(EntityStorageInterface $storage, array $entities)
 {
     $prefixes = ['feeds_feed_import', 'feeds_feed_parse', 'feeds_feed_process'];
     foreach ($entities as $entity) {
         foreach ($entity->getPlugins() as $plugin) {
             $plugin->onFeedTypeDelete();
         }
         // Delete any existing queues related to this type.
         foreach ($prefixes as $prefix) {
             if ($queue = \Drupal::queue($prefix . ':' . $entity->id())) {
                 $queue->deleteQueue();
             }
         }
     }
     // Clear the queue worker plugin cache to remove this derivative.
     \Drupal::service('plugin.manager.queue_worker')->clearCachedDefinitions();
 }