WP schedule with intervals - php

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' );

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_event() in plugin not scheduling a cron event

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.

Wordpress wp_schedule_event randomly between 30 and 60 minutes

Is is possible to start the WP-Cron randomly between 30 and 60 minutes?
What i have
add_action('my_hourly_event', 'do_this_hourly');
function my_activation()
{
if(!wp_next_scheduled( 'my_hourly_event' ))
{
wp_schedule_event( current_time( 'timestamp' ), 'hourly', 'my_hourly_event');
}
}
add_action('wp', 'my_activation');
function do_this_hourly()
{
// do something
}
Unfortunately the wp_schedule_event doesn't have 30 min and accepts only these intervals: hourly, twicedaily(12H), daily(24H).
In my opinion is a bit strange to have a scheduled event that can change randomly, and probably you should look at a different implementation.
Without discussing your choice I am going to provide a possible answer.
There are plugins with hooks into the Wordpress cron system to allow different time interval.
One solution is to set only one cron every 30 minutes and have a custom function that randomly will be executed or not.
if (rand(0,1)) { ....
For example:
after 30 min the function will be executed (and you have 30 min cron)
after another 30 min the function simply skip the run
for the next 30min will be triggered again and executed(and you have your 1 hour cron).
The problem there is to force the execution at 1 hour (after 1 skip), because you can end up to skip more than +30min. This can be achieved storing the value of the last execution.
Another solution is to have 2 cron (30 min and 1 hour) nearly in the same time and having a custom function that will trigger the 30 min if the 1 hour is not running and so on.
Here is a nice Wordpress cronjob plugin
If you need to store the cron execution safely in a Wordpress table you can use the Wordpress add_option function, with get_option and update_option to get and update its value.
In the code below, I'll be using activation hook instead of wp hook, feel free to use after_switch_theme if it's a theme your code resides in...
You can use wp_schedule_single_event() and simply add a single event to happen randomly between 30-60 minutes every time the event happens ;)
/**
* Registers single event to occur randomly in 30 to 60 minutes
* #action activation_hook
* #action my_awesome_event
*/
function register_event() {
$secs30to60min = rand( 1800, 3600 ); // Getting random number of seconds between 30 minutes and an hour
wp_schedule_single_event( time() + $secs30to60min, 'my_awesome_event' );
}
// Register activation hook to add the event
register_activation_hook( __FILE__, 'register_event' );
// In our awesome event we add a event to occcur randomly in 30-60 minutes again ;)
add_action( 'my_awesome_event', 'register_event' );
/**
* Does the stuff that needs to be done
* #action my_awesome_event
*/
function do_this_in_awesome_event() {
// do something
}
// Doing stuff in awesome event
add_action( 'my_awesome_event', 'do_this_in_awesome_event' );

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

How to clear an abandoned woocommerce cart

I came across this code for clearing a Woocommerce cart on certain page loads.
But, I wonder is there a way to clear the cart after it has been abandoned?
For triggering only on front page your function needs to look like this:
add_action( 'init', 'woocommerce_clear_cart_url' );
function woocommerce_clear_cart_url() {
global $woocommerce;
if ( is_front_page() && isset( $_GET['empty-cart'] ) ) {
$woocommerce->cart->empty_cart();
}
}
function is_front_page() returns true only on front page of your wordpress site. Also, you might detect any other page with function is_page() where you can pass any page title, ID or slug
From this question: Set WooCommerce Cart Expiration
From what I can see, WooCommerce 2.0.20 has a scheduled maintenance job that runs twice/day that will remove any cart sessions from the WordPress options table. The default expiration time is set to 48 hours from the time the user first created the cart. I'm guessing your standard WordPress scheduling routines (and server cron/at jobs) will need to be running properly for this to execute.
AFAIK there is no way to adjust the 48 hour rule via settings. You could write a filter in your theme or in an "adjacent" plugin.
I've adjusted the code a little bit to switch to a 24 hour session. I'm not sure you want to be deleting every few minutes as that has the potential to be performance-heavy.
add_filter('wc_session_expiring', 'so_26545001_filter_session_expiring' );
function so_26545001_filter_session_expiring($seconds) {
return 60 * 60 * 23; // 23 hours
}
add_filter('wc_session_expiration', 'so_26545001_filter_session_expired' );
function so_26545001_filter_session_expired($seconds) {
return 60 * 60 * 24; // 24 hours
}

Categories