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
Related
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
}
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.
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.
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' );
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!