• Home
  • Categories
    • WordPress Troubleshooting
    • WordPress Tips and Tricks
    • SSH (Secure Shell)
    • WordPress Insights
    • WordPress Common Facts
    • Securing WordPress
  • Series Tutorials
    • Advanced WordPress Topic
  • Privacy Policy
  • Terms of Use
  • Contact Me
  • About WP Tuts Hub
Home  /  Advanced WordPress Topic • Series Tutorials  /  Using Cron Job in WordPress – Schedule Events With WP-Cron: Part 1
Advanced WordPress Topic
December 20, 2016

Using Cron Job in WordPress – Schedule Events With WP-Cron: Part 1

zubaer Schedule Events, Using Cron Job, WordPress Cron Job, WP-Cron 2 Comments
Share on Facebook Share on Twitter Share on Pinterest Share on StumbleUpon Share on Reddit Share on LinkedIn Share on tumblr
Email this article!

In this part of this series, we are going to be introduced with Using Cron Job in WordPress and practice WP-Cron which is a fantastic way to schedule a Cron Job with WordPress. Now, there is a particular difference between regular Cron and WP-Cron. In the case of regular Cron, it runs in a specific time interval but WordPress does it in a slightly different way. Though WordPress allows you to set up a specific time interval, it won’t execute it until someone visits your website (they can be a human visitor, a search engine bot or you). So, in order to be run a WP-Cron the specified time must have to be passed and at the same time, someone must visit your website.

An example may help: Let’s think you have created a task which will send you an email in every 1 hour. Now, 1 hour (60 seconds) has passed, but you won’t receive an email if no one visits your website. If you now visit your website at 70 seconds, you will receive an email instantly. I hope this makes sense. Anyway, WP-Cron is really handy as it doesn’t require UNIX syntax to schedule a cron job and has many use cases if you want to recur a task. Okay, that’s a fair amount of intro, let’s get right into it.

Using Cron Job in WordPress – Schedule Events With WP-Cron:

To get started with WP-Cron, we will create a simple cron job which will write to file in every 1 hour.

<?php
/*
 * Plugin Name: WP Cron Test
 * Plugin URI: http://zubaer.com
 * Description: WP Cron Job Practice
 * Version: 1.0.0
 * Author: Md. Zubaer Ahammed
 * Author URI: http://zubaer.com
 */

add_action('init', function() {
	if(!wp_next_scheduled('wptutshub_cron_hook_hourly')) {
		wp_schedule_event(time(), 'hourly', 'wptutshub_cron_hook_hourly');
	}
});


add_action('wptutshub_cron_hook_hourly', function() {
	$current_time = time();
	$file = WP_PLUGIN_DIR."/wpcron/demofile.txt";
	$myfile = fopen($file, "w") or die("Unable to open file!");
	$txt = "This string was written (hourly) at $current_time.\n";
	fwrite($myfile, $txt);
	fclose($myfile);
});

?>

Explanations:

We are scheduling an event with wp_schedule_event($timestamp, $recurrence, $hook, $args) function which takes three arguments:

  1. $timestamp (required): we have used the current time with time() function.
  2. $recurrence (required): How often it will reoccur. WordPress supports three default value for it (We shall create custom recurrence shortly): hourly, twicedaily, daily
  3. $hook (required): Action hook to execute
  4. $args (optional): Optional arguments to pass to the hook function(s).

But we cannot just schedule a cron job and get done with it. Because it will register it on every page load (as we attached it with ‘init‘ hook). So, we are checking if it’s not scheduled for next already with wp_next_scheduled() function which takes the hook as a parameter. We are writing current time to a file named ‘demofile.txt‘ in our plugins root directory. We have used time() function as our $timestamp parameter. So, if we load any page (such as reload WP Dashboard or visit a web page), this Cron will write to that file.

Using Cron Job with WordPress WP-Cron

Creating Custom Time Interval:

So, alongside the default time intervals (hourly, twicedaily, daily), you may want to create your own custom time interval. Let's say we want to write to the file in every single minute. So, our code will be like below:

add_filter('cron_schedules', function($schedules) {
	$schedules['one-minute'] = array(
		'interval' => 60,
		'display' => 'Every Single Minute'
	);
	return $schedules;
});

Explanations: Here we are attaching a new interval with ‘cron_schedules‘ filter. An array ($schedules) containing all default intervals will be passed to the closure function to which we can add our own time interval. The name can be anything but the main thing is ‘interval‘ key which denotes the amount of time in seconds. And ‘display‘ is only for reading purposes if you want to read this interval later as an option.

Now, we have previously scheduled a Cron which runs hourly and writes to the file. If we don’t unschedule it, it will run eternally in every single hour. So, let’s see how to unschedule a Cron Job with WordPress.

Unschedule a Cron Job:

$time = wp_next_scheduled('wptutshub_cron_hook_hourly');
wp_unschedule_event($time, 'wptutshub_cron_hook_hourly');

Explanations:

First we are getting the time of the next scheduled event or when the event with ‘wptutshub_cron_hook_hourly’ is going to be run next. Then we unschedule it with ‘wp_unschedule_event()’ function which takes two parameters $time and $hook of the scheduled event/cron job.

So, Our Final Code will look like below:

<?php
/*
 * Plugin Name: WP Cron Test
 * Plugin URI: http://zubaer.com
 * Description: WP Cron Job Practice
 * Version: 1.0.0
 * Author: Md. Zubaer Ahammed
 * Author URI: http://zubaer.com
 */

/**
 * Hook it with 'init' hook (WordPress has fully loaded but it's hasn't sent any headers yet.)
 */
add_action('init', function() {

	//Unschedule an laready scheduled event which we did with 'hourly' time interval in the beginning of the article.
	$time = wp_next_scheduled('wptutshub_cron_hook_hourly');
	wp_unschedule_event($time, 'wptutshub_cron_hook_hourly');

	//Schedule an event which will run in every single minute.
	if(!wp_next_scheduled('wptutshub_cron_hook_minute')) {
		wp_schedule_event(time(), 'one-minute', 'wptutshub_cron_hook_minute');
	}
});

/**
 * Defining our hook.
 */
add_action('wptutshub_cron_hook_minute', function() {
	$current_time = time();
	$file = WP_PLUGIN_DIR."/wpcron/demofile.txt";
	$myfile = fopen($file, "a+") or die("Unable to open file!");
	$txt = "This string was written (per minute) at $current_time.\n";
	fwrite($myfile, $txt);
	fclose($myfile);
});

/**
 * Create custom schedule or time interval.
 */
add_filter('cron_schedules', function($schedules) {
	$schedules['one-minute'] = array(
		'interval' => 60,
		'display' => 'Every Single Minute'
	);
	return $schedules;
});

?>

In the next part this article we will see more about WP-Cron such as how to handle it from options page, displaying single events, scheduling a single event, etc. Also, you can contact me directly regarding any help.

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)

Related

Previous Article How to Secure WordPress Site From Hacking, DDoS and Brute Force Attack
Next Article Using Cron Job in WordPress – Schedule Events With WP-Cron: Part 2

About Author

zubaer

Hi, My name is Zubaer and I am a Web Devloper. Besides, I am Hybrid Mobile App Developer. My fields of proficiency are WordPress, Laravel, HTML, CSS, JavaScript, AngularJS and PHP. You can visit www.zubaer.com to know more about me.

Related Posts

  • WP Cron - All scheduled cron jobs

    Using Cron Job in WordPress – Schedule Events With WP-Cron: Part 2

2 Comments

  1. Pingback: Using Cron Job in WordPress – Schedule Events With WP-Cron: Part 2 - WP Tuts Hub
  2. Pingback: (Türkçe) Cronjob Nedir? Nasıl Kullanılır? - Ceyhun Enki Aksan

Leave a Reply

Cancel reply




Popular Posts

  • Using Cron Job in WordPress - - Schedule Events With WP-Cron
    Using Cron Job in WordPress – Schedule Events With WP-Cron: Part 1 December 20, 2016
  • C Program to Store Multiple Student Records Using Structure and Pointer May 27, 2023
  • SSH Secure Shell Commands
    Frequently Used SSH (Secure Shell) Commands for a Web Developer September 7, 2016
  • Update WordPress site URL via PHPmyadmin
    WordPress Replace Old URL After Domain Change September 27, 2016

Categories

  • Advanced WordPress Topic2
  • C Programming2
  • Computer Programming2
  • Securing WordPress2
  • Series Tutorials2
  • SSH (Secure Shell1
  • WordPress Common Facts1
  • WordPress Insights2
  • WordPress Tips and Tricks4
  • WordPress Troubleshooting3

Calorie Calculator Pro

  • US Units
  • Metric Units
Please enter your age
Please enter your gender
Please enter your height
Please enter your weight (Pounds)
Please select an activity level
Your body fat percentage (optional)
Please enter your First Name
Please enter your Last Name
Please enter your best email address
Please enter your age
Please enter your gender
Please enter your height
Please enter your weight (Kg)
Please select an activity level
Your body fat percentage (optional)
Please enter your First Name
Please enter your Last Name
Please enter your best email address
Please enter your best email address
Problem? Try Another

Archives

  • May 20233
  • July 20171
  • December 20162
  • September 20162
  • July 20162

Tags

File Upload Error HTTP Error Prevent DDoS and Brute Force Attack Schedule Events Secure Shell Securing WordPress SSH SSH Commands Structure and Pointers in C Structures in C Programming Using Cron Job WordPress Administrator WordPress Common Facts WordPress Cron Job WordPress Error WordPress Insights WordPress Tips WordPress Tricks WP-Cron

My Services and Products

  • Hire Me or Contact Me
  • My WordPress Plugins and Themes
  • WeboCoder
  • Privacy Policy
  • Terms of Use
  • About Us

Subscribe

    Your Name (required)

    Your Email (required)

    Random Posts

    • C Program to Store Multiple Student Records Using Structure and Pointer May 27, 2023
    • SSH Secure Shell Commands
      Frequently Used SSH (Secure Shell) Commands for a Web Developer September 7, 2016
    • http error with wordpress file upload
      How to Fix HTTP Error in WordPress (Different Possible Ways) July 25, 2016
    © WP Tuts Hub 2023.
     

    Loading Comments...