Italian (Italy)

Custom Cron Jobs

Cron Jobs Development

I lavori che possono essere eseguiti da VikBooking, dopo averli programmati con l'utilità di Cron Server, devono essere collocati nella directory seguente:

wp-content/plugins/vikbooking/administrator/cronjobs /

Segui lo schema seguente per vedere la struttura del file di classe:

Plugin structure

The native WordPress plugin should be basically a folder with one PHP file in the root of this directory (the main plugin file), another folder inside it (the container of the actual Cron Jobs for our plugin), and our custom Cron Jobs we want to develop and install (should be placed inside the "container folder").

Here's how the native WordPress plugin should be declared. This is the content of the "main plugin file".

<?php
/*
Plugin Name:  My Custom Cron
Plugin URI:   https://vikwp.com/
Version:      1.0
Author:       E4J s.r.l.
Author URI:   https://vikwp.com
License:      GPL2
License URI:  https://www.gnu.org/licenses/gpl-2.0.html
*/

// No direct access
defined('ABSPATH') or die('No script kiddies please!');

// You can optionally load any necessary PHP assets here

// Define the hook for Vik Booking to read Cron Jobs from the /cronjobs sub-directory
add_action('vikbooking_create_cron_jobs_factory', function($dummy, VBOCronFactory $factory)
{
	$factory->addIncludePath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'cronjobs');
}, 10, 2);

If you were to upload this PHP file onto the apposite /wp-content/plugins directory of your WordPress website, you would have a working plugin. However, we now need to add some actual Cron Jobs to our /cronjobs sub-directory, or no custom Cron Jobs would be installed.

Cron Job main file

A valid Cron Job for Vik Booking must declare a PHP class that follows a specific nomenclature depending on the file name, and it must extend a specific class available in our plugin by default in its core framework.

If you are willing to create a custom Cron Job called "Foo Bar Baz", then you should call the PHP file "foo_bar_baz.php", the class name would be "VikBookingCronJobFooBarBaz" and it should extend the PHP class "VBOCronJob". Not respecting one of these requirements will result into a failure, or maybe into a PHP Fatal Error.

This is how a complete and custom Cron Job can be created with custom admin parameters, and the capability of tracking a specific value to avoid duplicate notifications. This file foo_bar_baz.php should be placed inside the sub-directory /cronjobs.

<?php
/**
 * @package     VikBooking
 * @subpackage  com_vikbooking
 * @author      E4J srl
 * @copyright   Copyright (C) 2022 E4J srl. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE
 * @link        https://vikwp.com
 */

defined('ABSPATH') or die('No script kiddies please!');

class VikBookingCronJobFooBarBaz extends VBOCronJob
{
	use VBOCronTrackerArray;

	/**
	 * This method should return all the form fields required to collect the information
	 * needed for the execution of the cron job.
	 * 
	 * @return  array  An associative array of form fields.
	 */
	public function getForm()
	{
		return [
			'cron_lbl' => [
				'type'  => 'custom',
				'label' => '',
				'html'  => '<h4><i class="far fa-file-archive"></i>&nbsp;<i class="far fa-clock"></i>&nbsp;' . $this->getTitle() . '</h4>',
			],
			'maxchars' => [
				'type' => 'number',
				'label' => 'Maximum Characters',
				'help' => 'The maximum number of characters that can be stored within the list of processed elements.',
				'default' => 100,
				'min' => 0,
				'step' => 1,
			],
			'help' => [
				'type'  => 'custom',
				'label' => '',
				'html'  => '<p class="vbo-cronparam-suggestion"><i class="vboicn-lifebuoy"></i>Sample driver used to test the cron jobs extendability.</p>',
			],
		];
	}

	/**
	 * Returns the title of the cron job.
	 * 
	 * @return  string
	 */
	public function getTitle()
	{
		return 'Foo Bar - Baz';
	}
	
	/**
	 * Executes the cron job.
	 * 
	 * @return  boolean  True on success, false otherwise.
	 */
	protected function execute()
	{
		$this->maximumCharsTrackableElements = $this->params->get('maxchars', 100);
		
		$n = rand(0, 5);

		$this->appendLog("Registering [$n] numbers...");

		for ($i = 1; $i <= $n; $i++)
		{
			$elem = rand(0, 100);
			$result = $this->track($elem);
			$this->appendLog("Tracking element [$elem]: " . ($result ? 'Y' : 'N'));
		}

		if ($this->isDebug())
		{
			$dump = clone $this->getData();
			unset($dump->logs);
			echo '<pre>' . print_r($dump, true) . '</pre>';
		}

		return true;
	}
}

That's all a custom Cron Job should do. As you can see, there are some methods declared as abstract by the parent and abstract class "VBOCronJob". All you need to do with your custom Cron Job is to declare such methods according to your needs. Inside such methods, do not forget that you will be obviously able to use PHP native code, WordPress native functions, as well as to access the whole core framework of our plugin. This is thanks to the fact that your custom Cron Job will run within WP-Cron, so it's executed by WordPress itself.

Full plugin example

You can download a full copy of a working WordPress plugin that performs the same operations as described in the previous sections. This skeleton plugin will declare and install 2 custom Cron Jobs for Vik Booking:

  1. Foo Bar - Baz (file foo_bar_baz.php): uses a built-in trait to track a list of identifiers (such as a number for the booking ID) inside an array to avoid duplicate notifications.
  2. Stress - Tester (file stress_test.php): uses a built-in trait to not track anything, in case your Cron Job does not need to avoid duplicate notifications of the same elements.

Feel free to use the example that fits your needs the most.

You can download the full copy of the working plugin from this link. Once the plugin has been installed and activated, use Vik Booking to add a new Cron Job, and the two custom integrations will be available for selection.

This site uses cookies. By continuing to browse you accept their use. Further information