wp_schedule_event() in plugin not scheduling a cron event - php

I'm creating a WordPress plugin, when the plugin is activated I need a cron job to be scheduled to run every 5 minutes.
Here's my code;
// Register plugin activation hook
function my_plugin_activate() {
if( !wp_next_scheduled( 'my_function_hook' ) ) {
wp_schedule_event( time(), '5', 'my_function_hook' );
}
}
register_activation_hook( __FILE__, 'my_plugin_activate' );
// Register plugin deactivation hook
function my_plugin_deactivate(){
wp_clear_scheduled_hook('my_function_hook');
}
register_deactivation_hook(__FILE__,'my_plugin_deactivate');
// Function I want to run when cron event runs
function my_function(){
//Function code
}
add_action( 'my_function_hook', 'my_function');
When I use this plugin https://wordpress.org/plugins/wp-crontrol/ to check the cron events, nothing has been added, I'm expecting a cron event to be added that runs 'my_function' at 5 minute intervals, I have no errors

See: wp_schedule_event()
Valid values for the recurrence are hourly, daily, and twicedaily.
These can be extended using the ‘cron_schedules’ filter in
wp_get_schedules().
So you just need to add a custom schedule that runs every 5 minutes.
<?php // Requires PHP 5.4+.
add_filter( 'cron_schedules', function ( $schedules ) {
$schedules['every-5-minutes'] = array(
'interval' => 5 * MINUTE_IN_SECONDS,
'display' => __( 'Every 5 minutes' )
);
return $schedules;
} );
if( ! wp_next_scheduled( 'my_function_hook' ) ) {
wp_schedule_event( time(), 'every-5-minutes', 'my_function_hook' );
}

WP Cron runs, when somebody visits your website.
Thus if nobody visits, the cron never runs.
Now there are 2 solutions:
Disable WP Cron, use a real cron job and customize it.
https://support.hostgator.com/articles/specialized-help/technical/wordpress/how-to-replace-wordpress-cron-with-a-real-cron-job
Use a custom interval in wp_schedule_event():
function myprefix_custom_cron_schedule( $schedules ) {
$schedules['every_six_hours'] = array(
'interval' => 21600, // Every 6 hours
'display' => __( 'Every 6 hours' ),
);
return $schedules;
}
add_filter( 'cron_schedules', 'myprefix_custom_cron_schedule' );
//Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'myprefix_cron_hook' ) ) {
wp_schedule_event( time(), 'every_six_hours', 'myprefix_cron_hook' );
}
///Hook into that action that'll fire every six hours
add_action( 'myprefix_cron_hook', 'myprefix_cron_function' );
//create your function, that runs on cron
function myprefix_cron_function() {
//your function...
}
and you can see these tuts
http://www.nextscripts.com/tutorials/wp-cron-scheduling-tasks-in-wordpress/
http://www.iceablethemes.com/optimize-wordpress-replace-wp_cron-real-cron-job/
http://www.smashingmagazine.com/2013/10/16/schedule-events-using-wordpress-cron/
custom Wp cron
http://codex.wordpress.org/Plugin_API/Filter_Reference/cron_schedules
http://www.smashingmagazine.com/2013/10/16/schedule-events-using-wordpress-cron/
http://www.viper007bond.com/2011/12/14/how-to-create-custom-wordpress-cron-intervals/
http://www.sitepoint.com/mastering-wordpress-cron/
https://tommcfarlin.com/wordpress-cron-jobs/
http://www.paulund.co.uk/create-cron-jobs-in-wordpress
cron linux
http://www.cyberciti.biz/faq/how-do-i-add-jobs-to-cron-under-linux-or-unix-oses/
http://www.thesitewizard.com/general/set-cron-job.shtml
http://code.tutsplus.com/tutorials/scheduling-tasks-with-cron-jobs--net-8800
google search

As #dingo_d commented, WordPress Cron doesn't work like server Cron. the WordPress Cron runs on page load. It checks the database for a scheduled event and if an event is scheduled it runs the task. So if nobody visits the website in a 5 minute time period no job will be run in that period. When someone does visit the website, the page load process runs and the scheduled event takes place.
It was setup like this so WordPress would work without needing any particular Cron functionality on the server.
To circumvent this you can use a service that automatically visit your website or you could setup a Cron script on your server to automatically load the page.
Assuming a linux server you ssh into the terminal then write crontab -e and hit enter. You'll enter the cron file for setting up cron jobs. Add to the file the following line:
/5 * * * wget -q -O - http://yourdomain.com/wp-cron.php?doing_wp_cron
substituting http://yourdomain.com for your actual website. This ensures your website is visited every 5 minutes.
I grabbed the information on how to do this from https://tommcfarlin.com/wordpress-cron-jobs/ so credit to him and that link has lots more WordPress cron info.

Related

Wordpress Cron Job: Ignore Cron job during the site's inactivity period

I did Cron job to fetch data from API every minute
But I am facing a problem which is when the site is inactive, a number of tasks that have not been implemented are saved, and when the site becomes active, all of these tasks are executed.
Is there a way for me to ignore all operations during the period of inactivity and request api once and follow up on the continuation of the Cron job
I am referring to accumulated scheduler actions that then all execute at once, when the next visitor comes
function my_schedules($schedules){
if(!isset($schedules["my1min"])){
$schedules["my1min"] = array(
'interval' => 60,
'display' => __('Once every 1 min'));
}
return $schedules;
}
add_filter('cron_schedules','my_schedules');
wp_schedule_event(strtotime('01:00:00'), 'my1min', 'callback_scheduled_my');
add_action( 'callback_scheduled_my', 'callback_scheduled_my' );
function callback_scheduled_my(){
//my code
}

WP schedule with intervals

I have Wordpress website with the Woocommerce plugin.
I developed plugin with function that runs while loop to go through my 3,000 products.
The function changes the price of the products by external data (it compares prices of competitors).
Everything works great, i succeed, the function runs and the scraper is great.. but, now i understand that the external website allowed me to scrape only once per 10 seconds.
Also, i need this function to run once per 4 hours.
What is the best way to achieve this goal?
Summary:
I need the function to run once per 4 hours
On each run (once per 4 hours) i need the function to "rest" for 10 seconds.
I already set successfully the cron job of the 4 hours run, but i can't understand how to make this while loop to "rest" for 10 seconds. I tried to use sleep(10) function, but its stop to run after 10 times i guess because "execution time" limit of my server.
function isa_add_every_four_hours_getCompetitorsPrices( $schedules ) {
$schedules['every_four_hours'] = array(
'interval' => 14400,
'display' => __( 'Every 4 hours', 'textdomain' )
);
return $schedules;
}
if ( ! wp_next_scheduled( 'isa_add_every_four_hours_getCompetitorsPrices' ) ) {
wp_schedule_event( time(), 'every_four_hours', 'isa_add_every_four_hours_getCompetitorsPrices' );
}
// Hook into that action that'll fire every 4 hours
add_action( 'isa_add_every_four_hours_getCompetitorsPrices', 'my_cronjob_walker_zs_gzp' );

Executing custom php file from Cron, implementing Wordpress mail send

I'm building a sort of selfservice portal, and need to implement it on a wordpress site. The portal itself, is build in pure php, jquery, sql etc. Without the use of the Wordpress libraries, which the rest of the main site rests on.
I've searched the web, trying to find what i need, but i couldn't find a match.
So.. What am i trying to do..
I need to run a Cron job every X day at X clock, triggering a custom PHP file in the root on the server (lets call it portal_reminder.php), which then uses the built in (or a plugin?) to send e-mails to the target specified in the custom PHP file.
Oh, as the server is hosted in a serverpark using multi-hosts, i'm not allowed to install any "external" programs (sendmail), nor can i create custom cronjobs in the terminal (cron -e).
So, i need a wordpress cron plugin to do the cron handling, aswell as wordpress/other to handle the e-mails.
For clarification, my idea was as follows:
Cronjob triggers "portal_reminder.php"
Portal reminder triggers "mailsender", including $to, $from, $content (html content)
"mailsender" sends the mail :)
Is this even possible?
Cron jobs works well with WordPress, even if a server cron is better. WordPress cron will trigger when someone visits your WordPress site.
Here is an example with a new schedule (WordPress native schedules are only daily, twicedaily, hourly):
add_filter( 'cron_schedules', 'wc_dsr_add_custom_cron_schedule' );
function wc_dsr_add_custom_cron_schedule( $schedules ) {
$schedules['fourdaily'] = array(
'interval' => 21600, // 86400s/4
'display' => __( 'Four time daily' ),
);
return $schedules;
}
function wc_dsr_create_daily_backup_schedule(){
//Use wp_next_scheduled to check if the event is already scheduled
$timestamp = wp_next_scheduled( 'wc_dsr_cron_send_action' );
//If $timestamp == false schedule daily backups since it hasn't been done previously
if( $timestamp == false ){
//Schedule the event for right now, then to repeat daily using the hook 'wc_create_daily_backup'
wp_schedule_event( time(), 'fourdaily', 'wc_dsr_cron_send_action' );
}
}
//Hook our function , wc_dsr_cron_send_action(), into the action wc_dsr_cron_send_report
add_action( 'wc_dsr_cron_send_action', 'wc_dsr_cron_send_report' );
function wc_dsr_cron_send_report(){
// do your job
wp_mail('test#test.com', 'Subject', 'Message');
}
In your case, wc_dsr_cron_send_report() might include and work with portal_reminder.php. To work well with WordPress function, you must add this to portal_reminder.php
define( 'WP_USE_THEMES', false );
require_once('pathto/wp-load.php);
You'll be able to find more example on the web.

WordPress Scheduling Not Firing

I want to echo a string after a time period using WordPress scheduling. Below is my code in functions.php. Nothing gets printed through echo statement and also there is no error. Please guide what am I doing wrong.
function add_new_intervals($schedules) {
// add weekly and monthly intervals
$schedules['now'] = array(
'interval' => 1,
'display' => __('Once Weekly')
);
return $schedules;
}
add_filter( 'cron_schedules', 'add_new_intervals');
function my_activation() {
if ( !wp_next_scheduled( 'my_hourly_event' ) ) {
wp_schedule_event( current_time( 'timestamp' ),'now', 'my_hourly_event');
}
}
add_action('wp', 'my_activation');
add_action('my_hourly_event', 'do_this_hourly');
function do_this_hourly() {
echo "This is the Text";
}
One thing you are doing wrong is expecting to be able to see something echo when a cron job is run. A better test would be to have it make a change in the database, something like:
`update_option('my_cron_test', current_time())`;
WP Cron jobs (like most cron jobs) are intended to run a function in the that needs to happen on a schedule. They are not intended to create "user output".
Some Tips with WP Cron Jobs:
Your code will attempt to run that function once per hour, but the way WP is set up, it may (or may not) run, depending on if the site gets visited.
There are many solutions to this weakness, the simplest / most effective being to set up a crontab job on your server that triggers the WP cron. Something like so:
/15 * * * wget -q -O - http://yourdomain.com/wp-cron.php?doing_wp_cron
For more help with this (it can be tricky), check out these articles:
Properly Setting Up WP Cron Jobs
Mastering WP Cron

wordpress wp_schedule_event without traffic

I have a question, I write an plugin with function that will send mail to customers after x days. I created the function.
Now, I need that the function will run only once a day.
Here is the code:
register_activation_hook(__FILE__, 'my_activation');
add_action('my_hourly_event', 'do_this_hourly');
function my_activation() {
wp_schedule_event( current_time( 'timestamp' ), 'hourly', 'my_hourly_event');
}
function do_this_hourly() {
// do something every hour
}
From this link: http://www.paulund.co.uk/create-cron-jobs-in-wordpress
But the schedule works only when there is traffic on the site, which means that if I closed the browser, after one hour the function doesn't run and the email doesn't sent.
It's possible to run cron job with Wordpress?
Thanks!

Categories