1

I'm pretty new to drupal and was tasked with setting up a cron job to run every hour. I have the php file which generates an xml file that will be used on a different site.

My question is: Do I put mycron.php in the root (same as cron.php) and configure the crontabs to run mycron.php every hour?

Any guidance is appreciated.

2 Answers 2

2

You can write your own cron job using hook_cron() in your custom module and set it up with the project module Elysia Cron, for timing and frequencies of each cron task.

1

Initially I came to this page with a similar question. This is basically what I found out.

You don't run cron jobs from your PHP code, you run cron jobs from the server operating system. Cron jobs can only be set in Linux, Unix or macOS, windows doesn't come with a preinstalled cron system.

You set up cron jobs either from your operating system (ubuntu for instance) if you are using a VPS. Or if you are using shared hosting you will most likely be able to set up your cron jobs from the admin menu in your account, which will be dependent on your hosting provider.

What you do is that you create an endpoint in your Drupal module hook_menu. The endpoint in the menu should be linked to a callback function that will perform the actions you want periodically to run.

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,
    ]
  ];
}

Check the hook_menu link to see what the elements in the functions return array do.

/**
 * 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
}

In the cron job you are going to set up you will have to point your cron job to the endpoint location. The cron job in the example below will run, one minute past 4 on each first day of January and every Monday in January (minute, hour, day of the month, month, day of the week):

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

(example from the Drupal documentation, do a man wget to find out what the wget options do)

Edit: You obviously also have the hook_cron option. Where you put your code in a ..._cron() {} function which will be run whenever the page wide cron job is run but what doesn't leave you with a lot of control.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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