5

I am doing a module in drupal 8, I would like to know how to execute a function automatically every month. I think it's done with Cron, but I only get to do it every week. as I edit it from my function.

  • please revise your question it is not clear what you want to do ... – GiorgosK Mar 27 '18 at 22:53
9

A modified example from cron_example module. This doesn't concern the interval the cron tasks are set in cron.

This is important, as you will probably set another cron tasks sooner or latter with different interval requirements. Also, many system tasks require more frequent cron runs.

function cron_example_cron() {
  $interval = 30*24*60*60; // Approx a month of interval

  // We usually don't want to act every time cron runs (which could be every
  // minute) so keep a time for the next run in the site state.
  $next_execution = \Drupal::state()->get('cron_example.next_execution');
  $next_execution = !empty($next_execution) ? $next_execution : 0;
  if (REQUEST_TIME >= $next_execution) {
    // This is a silly example of a cron job.
    // It just makes it obvious that the job has run without
    // making any changes to your database.
    \Drupal::logger('cron_example')->notice('cron_example ran');
    if (\Drupal::state()->get('cron_example_show_status_message')) {
      drupal_set_message(t('cron_example executed at %time', ['%time' => date_iso8601(REQUEST_TIME)]));
      \Drupal::state()->set('cron_example_show_status_message', FALSE);
    }
    \Drupal::state()->set('cron_example.next_execution', REQUEST_TIME + $interval);
  }
}

Also, for more fine-tuned approach, you can use the Ultimate Cron module, which provides more fine-grained control for the cron jobs.

| improve this answer | |
  • Followed this method to send a file to external server daily at 10.30 AM.But the cron didn't run as expected.Tried even without a scheduled time.No luck. Based on the cron logs, the cron is not triggered at the scheduled time.Any suggestion will be helpful. – developer Jul 21 at 18:26
1

The best way to run cron every month is by adding the following command to your crontab.

0 0 1 * * wget -O - -q -t 1 http://CRON_URL

http://CRON_URL is replaced with a URL which is different for each Drupal version. For D8 it looks something like http://www.example.com/cron/. You can get this URL from Status report — Reports Administration > Reports > Status (/admin/reports/status)

For more info please visit https://www.drupal.org/docs/7/setting-up-cron-for-drupal/configuring-cron-jobs-using-the-cron-command

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.