I am building a Drupal 6 module for a client and I want to execute some part of code every XYZ minutes. I know I can implement the cron_hook, but my module has no control over the client's cron. I need to run my code irrespective of cron setting. Any ideas on how to approach this?
Drupal doesnt really offer anything beyond the hook_cron functionality.
However, what you can do is define a normal menu callback that executes whatever aribitarary code you want to run. Just set up the job manually in your server's cron-tab to fire it whenever you want
<?
function example_menu() {
$items = array();
$items['example/cron'] = array(
'title' => 'example Cron',
'page callback' => 'example_callback',
'type' => MENU_CALLBACK,
);
}
function example_callback(){
//optionally do some IP checking to make sure its not being fired by a remote request
set_time_limit(0); //set it so your cron wont time out if it takes a long time to process ... be careful your cron doesnt run forever though
watchdog('example', "Cron Started", array(), WATCHDOG_NOTICE);
//execute custom code here
for($i = 0; $i < 100; $i++){
//do stuff
}
watchdog('example', "Cron Complete", array(), WATCHDOG_NOTICE);
}
Once you have that, just set up a cron job to hit the url however often you want
X Y * * * curl http://examplesite.com/example/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.
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
I have a script that sends out a push notification to users based on whats in a PHP file.
This is that file ...the parts that matter ...
$doc = new DOMDocument();
$doc->load('RandomXML Url location here ');
$arrFeeds = array();
foreach ($doc->getElementsByTagName('item') as $node) {
$itemRSS = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue
);
array_push($arrFeeds, $itemRSS);
}
// APPLE APNS EXAMPLE 1
$apns->newMessage(2);
$apns->addMessageAlert($itemRSS['title']);
// $apns->addMessageCustom('acme2', array('bang', 'whiz'));
$apns->queueMessage();
// SEND ALL MESSAGES NOW
$apns->processQueue();
So thats the PHP that sends out the notification. It sends out the notification when this PHP script is loaded.
It loads the first post from the feed and sends it out. I want to send a notification out every time the RSS feed is updated with a new post. If it is updated with a new feed, then I want to run the above code.
So how can I do that and make sure it is run frequently?
I would really like to see what code I need to check if its updated? I don't know how to check for updates though and thats probably the most important part of the script.
Configure Cron to run your script every e.g. 1 hour and in script add code to check is RSS modified.
EDIT:
1. You can configure Cron to run your script every e.g. 1 hour.
2. To the script, add the code to test whether the RSS has been modified.
3. To check whether the feed was changed use the tag. You can save the tag content to txt and compare it.
4. To write tag content you can use SimpleXML and fwrite.