Wie führe ich alle 5 Minuten eine Funktion aus?
-
-
Sie sollten z.Linux-Cron- oder Cron-Dienste von Drittanbietern,wenn Sieein so kurzes Intervall und Genauigkeitbenötigen,You better look into e.g. Linux cron or 3rd party cron services if you need such a short interval and accuracy,
- 0
- 2015-11-10
- birgire
-
Die Site hat viel Verkehr. Siemüssen also das Zeitintervallnichtberücksichtigen. Stellen Sie sicher,dasses alle 2 oder 3 Minuten ausgelöst wird. Clientsbevorzugen dies über `functions.php`site havs heavy traffic.. so no need to consider the time interval.. sure it will be triggered for every 2 or 3 minutes.. clients prefer to do it from `functions.php`
- 0
- 2015-11-10
- Foolish Coder
-
Esistnichtmöglich,eine PHP-Datei auszulösen,ohne dassetwasmit einem Timer auf dem Server läuft.its not possible to trigger a php file without something running on the server with a timer.
- 0
- 2015-11-10
- Andrew Welch
-
Datei?Wir sprechen übereine Funktionin functions.phpfile? we are talking about a function in functions.php
- 0
- 2015-11-10
- Foolish Coder
-
Denken Sie,dassein kostenloser Überwachungsdienst der Ping sein könnte,der CRON auslöst?http://newrelic.com/server-monitoringDo you think a free monitoring service could be the ping that triggers CRON? http://newrelic.com/server-monitoring
- 0
- 2016-01-30
- jgraup
-
7 Antworten
- Stimmen
-
- 2016-01-29
Über cron_schedules können Sieneue Zeitplanzeitenerstellen:
function my_cron_schedules($schedules){ if(!isset($schedules["5min"])){ $schedules["5min"] = array( 'interval' => 5*60, 'display' => __('Once every 5 minutes')); } if(!isset($schedules["30min"])){ $schedules["30min"] = array( 'interval' => 30*60, 'display' => __('Once every 30 minutes')); } return $schedules; } add_filter('cron_schedules','my_cron_schedules');
Jetzt können Sie Ihre Funktionplanen:
wp_schedule_event(time(), '5min', 'my_schedule_hook', $args);
Umesnureinmal zuplanen,schließen Sieesin eine Funktionein und überprüfen Sie,bevor Siees ausführen:
$args = array(false); function schedule_my_cron(){ wp_schedule_event(time(), '5min', 'my_schedule_hook', $args); } if(!wp_next_scheduled('my_schedule_hook',$args)){ add_action('init', 'schedule_my_cron'); }
Beachten Sie den Parameter $ args! Wenn Sie den Parameter $ argsnichtin wp_next_scheduled angeben,aber $ argsfür wp_schedule_event haben,wirdeine nahezu unendliche Anzahl desselben Ereignissesgeplant (anstelle vonnureinem).
Erstellen Sie abschließend dieeigentliche Funktion,die Sie ausführenmöchten:
function my_schedule_hook(){ // codes go here }
Ich denke,esist wichtig zuerwähnen,dass wp-cronbei jedem Ladeneiner Seite den Zeitplan überprüft undfälligegeplante Jobs ausführt.
Wenn Sie alsoeine Websitemit wenig Verkehr haben,dienur 1 Besucherpro Stunde hat,wird wp-cronnur ausgeführt,wenn dieser Besucher Ihre Website durchsucht (einmalpro Stunde). Wenn Sieeine starkfrequentierte Website haben,auf der Besucherjede Sekundeeine Seite anfordern,wirdjede Sekunde wp-cron ausgelöst,wodurch der Server zusätzlichbelastet wird.
Die Lösungbesteht darin,wp-cron zu deaktivieren und übereinen echten cron-Jobin dem Zeitintervall auszulösen,in dem Sie dengeplanten wp-cron-Job am schnellsten wiederholen (in Ihrem Fall 5 Minuten).
Lucas Rolff erklärt das Problem undgibt die Lösungim Detail an .
Alternativ können Sieeinen kostenlosen Drittanbieter-Service wie UptimeRobot verwenden,um Ihre Website abzufragen (und wp- auszulösen). cron) alle 5 Minuten,wenn Sie wp-cronnicht deaktivieren und übereinen echten Cron-Job auslösenmöchten.
You can create new schedule times via cron_schedules:
function my_cron_schedules($schedules){ if(!isset($schedules["5min"])){ $schedules["5min"] = array( 'interval' => 5*60, 'display' => __('Once every 5 minutes')); } if(!isset($schedules["30min"])){ $schedules["30min"] = array( 'interval' => 30*60, 'display' => __('Once every 30 minutes')); } return $schedules; } add_filter('cron_schedules','my_cron_schedules');
Now you can schedule your function:
wp_schedule_event(time(), '5min', 'my_schedule_hook', $args);
To only schedule it once, wrap it in a function and check before running it:
$args = array(false); function schedule_my_cron(){ wp_schedule_event(time(), '5min', 'my_schedule_hook', $args); } if(!wp_next_scheduled('my_schedule_hook',$args)){ add_action('init', 'schedule_my_cron'); }
Note the $args parameter! Not specifying the $args parameter in wp_next_scheduled, but having $args for wp_schedule_event, will cause an almost infinite number of the same event to be scheduled (instead of just one).
Finally, create the actual function that you would like to run:
function my_schedule_hook(){ // codes go here }
I think it is important to mention that wp-cron is checking the schedule and running due scheduled jobs each time a page is loaded.
So, if you have a low traffic website that only has 1 visitor an hour, wp-cron will only run when that visitor browses your site (once an hour). If your have a high traffic site with visitors requesting a page every second, wp-cron will be triggered every second causing extra load on the server.
The solution is to deactivate wp-cron and trigger it via a real cron job in the time interval of you fastest repeating scheduled wp-cron job (5 min in your case).
Lucas Rolff explains the problem and gives the solution in detail.
As an alternative, you could use a free 3rd party service like UptimeRobot to query your site (and trigger wp-cron) every 5 minutes, if you do not want to deactivate wp-cron and trigger it via a real cron job.
-
- 2015-11-10
Wenn Ihre Site starkfrequentiert wird,können Sie versuchen,siemit
set_transient()
(ungefähr) alle 5 Minuten auszuführen,z. B.:function run_every_five_minutes() { // Could probably do with some logic here to stop it running if just after running. // codes go here } if ( ! get_transient( 'every_5_minutes' ) ) { set_transient( 'every_5_minutes', true, 5 * MINUTE_IN_SECONDS ); run_every_five_minutes(); // It's better use a hook to call a function in the plugin/theme //add_action( 'init', 'run_every_five_minutes' ); }
If your site does get heavy traffic then you could try using
set_transient()
to run it (very approximately) every 5 minutes, eg:function run_every_five_minutes() { // Could probably do with some logic here to stop it running if just after running. // codes go here } if ( ! get_transient( 'every_5_minutes' ) ) { set_transient( 'every_5_minutes', true, 5 * MINUTE_IN_SECONDS ); run_every_five_minutes(); // It's better use a hook to call a function in the plugin/theme //add_action( 'init', 'run_every_five_minutes' ); }
-
Nun,ähm,ja?! ...Well, er, yeah?!...
- 0
- 2015-11-10
- bonger
-
Ja,esfunktioniert NICHT. Ich habe denfolgenden Codein `functions.php` verwendet,wennein Besuch auf der Seiteerfolgt. Eine Tabellein meiner Datenbank wird aktualisiert. `function run_evry_five_minutes () {$ homepage=file_get_contents ('linkto visit');echo $ homepage;} `.Die DB-Tabelle wirdjedoch auchnach 6 Minutennicht aktualisiert.yeah., it's NOT working.. i've used following code in `functions.php` when a visit make to the page, an update will be made to a table in my database.. `function run_evry_five_minutes() { $homepage = file_get_contents('link to visit'); echo $homepage; }`. But the DB table is not updated after 6 minutes even.
- 0
- 2015-11-10
- Foolish Coder
-
Ich weißnicht,warumesbei Ihnennichtfunktioniert,aber wenn Sie darübernachdenken,nur `get_transient ()`/`set_transient ()` ohne das Cron-Zeug zu verwenden,ist das viel sinnvoller,vieleinfacher,wird die Antwort aktualisieren ...Don't know why it's not working for you but actually thinking about it just using `get_transient()`/`set_transient()` without the cron stuff makes a lot more sense, much simpler, will update answer...
- 0
- 2015-11-10
- bonger
-
@bongerist diesegute Alternativefür wp_schedule_event ()?@bonger is this good alternative for wp_schedule_event() ?
- 0
- 2016-05-08
- Marko Kunic
-
@ MarkoKunić Weißnicht,umehrlich zu sein,habeesnicht ausprobiert ...es wurdenur als Workaround angeboten,aber wenn Siees ausprobieren,lassen Siees uns wissen ...!(Die Antwort von Johano Fierra siehtgut aus http://wordpress.stackexchange.com/a/216121/57034)@MarkoKunić Don't know to be honest, haven't tried it... it was only offered as a workaround but if you try it out let us know...! (Johano Fierra's answer looks good http://wordpress.stackexchange.com/a/216121/57034 )
- 0
- 2016-05-09
- bonger
-
@bongeresfunktioniert,aberesist dasgleiche,wenn Sienicht auf der Website sind,wirdesnicht ausgeführt@bonger it is working, but it is the same thing, if you are not on website, it won't run
- 0
- 2016-05-10
- Marko Kunic
-
Nunja,wie an verschiedenen Stellen auf dieser Seiteerwähnt,benötigen Sieeinen echten Cron-Jobin irgendeiner Form,um Besucher zuerledigen ... (dankefür das Feedback.)Well yes as mentioned in various places on this page you need a real cron job of some form or other to do it without requiring visitors....(thanks for the feedback though.)
- 0
- 2016-05-11
- bonger
-
- 2018-03-05
Sie könnenesbei der Plugin-Aktivierung anstattbei jedem Plugin-Aufruf auslösen:
//Add a utility function to handle logs more nicely. if ( ! function_exists('write_log')) { function write_log ( $log ) { if ( is_array( $log ) || is_object( $log ) ) { error_log( print_r( $log, true ) ); } else { error_log( $log ); } } } /** * Do not let plugin be accessed directly **/ if ( ! defined( 'ABSPATH' ) ) { write_log( "Plugin should not be accessed directly!" ); exit; // Exit if accessed directly } /** * ----------------------------------------------------------------------------------------------------------- * Do not forget to trigger a system call to wp-cron page at least each 30mn. * Otherwise we cannot be sure that trigger will be called. * ----------------------------------------------------------------------------------------------------------- * Linux command: * crontab -e * 30 * * * * wget http://<url>/wp-cron.php */ /** * Add a custom schedule to wp. * @param $schedules array The existing schedules * * @return mixed The existing + new schedules. */ function woocsp_schedules( $schedules ) { write_log("Creating custom schedule."); if ( ! isset( $schedules["10s"] ) ) { $schedules["10s"] = array( 'interval' => 10, 'display' => __( 'Once every 10 seconds' ) ); } write_log("Custom schedule created."); return $schedules; } //Add cron schedules filter with upper defined schedule. add_filter( 'cron_schedules', 'woocsp_schedules' ); //Custom function to be called on schedule triggered. function scheduleTriggered() { write_log( "Scheduler triggered!" ); } add_action( 'woocsp_cron_delivery', 'scheduleTriggered' ); // Register an activation hook to perform operation only on plugin activation register_activation_hook(__FILE__, 'woocsp_activation'); function woocsp_activation() { write_log("Plugin activating."); //Trigger our method on our custom schedule event. if ( ! wp_get_schedule( 'woocsp_cron_delivery' ) ) { wp_schedule_event( time(), '10s', 'woocsp_cron_delivery' ); } write_log("Plugin activated."); } // Deactivate scheduled events on plugin deactivation. register_deactivation_hook(__FILE__, 'woocsp_deactivation'); function woocsp_deactivation() { write_log("Plugin deactivating."); //Remove our scheduled hook. wp_clear_scheduled_hook('woocsp_cron_delivery'); write_log("Plugin deactivated."); }
You can trigger it in plugin activation instead of on each plugin call:
//Add a utility function to handle logs more nicely. if ( ! function_exists('write_log')) { function write_log ( $log ) { if ( is_array( $log ) || is_object( $log ) ) { error_log( print_r( $log, true ) ); } else { error_log( $log ); } } } /** * Do not let plugin be accessed directly **/ if ( ! defined( 'ABSPATH' ) ) { write_log( "Plugin should not be accessed directly!" ); exit; // Exit if accessed directly } /** * ----------------------------------------------------------------------------------------------------------- * Do not forget to trigger a system call to wp-cron page at least each 30mn. * Otherwise we cannot be sure that trigger will be called. * ----------------------------------------------------------------------------------------------------------- * Linux command: * crontab -e * 30 * * * * wget http://<url>/wp-cron.php */ /** * Add a custom schedule to wp. * @param $schedules array The existing schedules * * @return mixed The existing + new schedules. */ function woocsp_schedules( $schedules ) { write_log("Creating custom schedule."); if ( ! isset( $schedules["10s"] ) ) { $schedules["10s"] = array( 'interval' => 10, 'display' => __( 'Once every 10 seconds' ) ); } write_log("Custom schedule created."); return $schedules; } //Add cron schedules filter with upper defined schedule. add_filter( 'cron_schedules', 'woocsp_schedules' ); //Custom function to be called on schedule triggered. function scheduleTriggered() { write_log( "Scheduler triggered!" ); } add_action( 'woocsp_cron_delivery', 'scheduleTriggered' ); // Register an activation hook to perform operation only on plugin activation register_activation_hook(__FILE__, 'woocsp_activation'); function woocsp_activation() { write_log("Plugin activating."); //Trigger our method on our custom schedule event. if ( ! wp_get_schedule( 'woocsp_cron_delivery' ) ) { wp_schedule_event( time(), '10s', 'woocsp_cron_delivery' ); } write_log("Plugin activated."); } // Deactivate scheduled events on plugin deactivation. register_deactivation_hook(__FILE__, 'woocsp_deactivation'); function woocsp_deactivation() { write_log("Plugin deactivating."); //Remove our scheduled hook. wp_clear_scheduled_hook('woocsp_cron_delivery'); write_log("Plugin deactivated."); }
-
- 2015-11-10
Ichbefürchte,dass dieeinzige andere Möglichkeit,außer darauf zu warten,dassjemand Ihre Sitebesucht,auf dereine Funktion ausgeführt wird,darinbesteht,einen Cron-Job auf Ihrem Servermit soetwas wieeinem https://stackoverflow.com/questions/878600/how-to-create-cronjob-using-bash oder wenn SieHaben Sieeine Schnittstelleim Cpanel-Stil auf Ihrem Server,manchmalgibt eseine Benutzeroberfläche zum Einrichten.
I'm afraid that other than waiting for someone to visit your site which runs a function, the only other option is to set up a cron job on your server using something like this https://stackoverflow.com/questions/878600/how-to-create-cronjob-using-bash or if you have a cpanel style interface on your server, sometimes there is a gui for setting this up.
-
Ja,ich verstehe das. Ich habebereitseinige Cron aus cPnaelerstellt. Aberjetzt versucheich,eine Funktion von `functions.php` auszuführen,weil sich die Funktionin einem` Plugin` oderin`functions.phpbefindet`Wir können Kundennichtbitten,einen Cron von cpanel selbsteinzurichten.yeah,., I understand that.. I already have some crons created from cPnael.. but now I am trying to run a function from `functions.php` because when the function is in a `plugin` or in `functions.php` we can not ask clients to set up a cron from cpanel on their own..
- 0
- 2015-11-10
- Foolish Coder
-
- 2016-01-30
Mit dem Cronjob Scheduler -Plugin können Sie häufige Aufgaben zuverlässig und zeitnah ausführen,ohne dass diesjemandtunmussBesuchen Sie Ihre Website. Siebenötigen lediglichmindestenseine Aktion undeinen Unix Crontab-Zeitplan.
Esist sehreinfach zubedienen und sehrflexibel.Sieerstellen Ihreeigene Funktion und definieren darineine Aktion.Anschließend können Sie Ihre Aktion aus dem Plugin-Menü auswählen undjederzeit auslösen.
The Cronjob Scheduler plugin allows you to run frequent tasks reliably and timely without anyone having to visit your site, all you need is at least 1 action and a Unix Crontab schedule.
It's very easy to use, and very flexible. You create your own function, and define an action within it. Then you can choose your action from the plugin menu and fire it whenever you want.
-
- 2015-11-10
Ich habeeine mögliche Lösungmit einer Zeitplanfunktion undeiner rekursiven WP Ajax-Funktion.
- Erstellen Sieein Zeitplanereignis von 60 Minuten,umeine Funktion auszuführen.
- Diese Funktion lösteine rekursive Funktionmit Ajax über
file_get_contents()
aus
- Die Ajax-Funktion verfügt übereinen Zählerin der Datenbankmit einer Gesamtzahl von 60 (fürjede Minuteinnerhalb der Stunde).
- Diese Ajax-Funktion überprüft Ihren Zähler auf:
Wenn der Zählergleich oder höher als 60ist,wird der Zähler zurückgesetzt und auf dennächsten Cron-Jobgewartet.
Wenn Sieein Vielfaches von 5 (also alle 5 Minuten) zählen,wird diegewünschte Funktion ausgeführt.
Undneben den Bedingungen wirdes 59 Sekunden lang schlafen.
sleep(59);
(vorausgesetzt,Ihre Funktionist schnell). Nach dem Ruhezustand löstes sicherneutmitfile_get_contents()
aus.Wichtige Dinge zubeachten:
- Erstellen Sieeine Möglichkeit,den Prozess zu unterbrechen (d. H. Einen Wertin der Datenbank zu überprüfen)
- Erstellen Sieeine Möglichkeit,um 2 Prozessegleichzeitig zu verhindern.
- Legen Sie unterfile_get_contents das Zeitlimitfür den Header auf 2 oder 3 Sekundenfest,da sonst auf dem Servermöglicherweise verschiedene Prozesse aufnichts warten
- Möglicherweisemöchten Sie den
set_time_limit(90);
verwenden,um zu verhindern,dass der Server Ihre Funktion vor dem Ruhezustand unterbricht
Esisteine Lösung,keinegute,und sie wirdmöglicherweise vom Serverblockiert. Miteinem externen Cron können Sieeine einfache Funktionfestlegen,und der Server verwendet alle 5 Minuteneinmal Ressourcen. Bei Verwendung dieser Lösung verwendet der Server ständig Ressourcen.
I have a possible solution using a schedule function and a recursive WP Ajax function.
- Create a schedule event of 60 minutes to run a function
- This function will trigger a recursive function using Ajax through
file_get_contents()
- The ajax function will have a counter on the database with a total number of 60 (for each minute inside the hour).
- This ajax function will check your counter to:
If counter equal or higher than 60 it will reset counter and await for the next cron job.
If counter multiple of 5 (so at each 5 minutes) it will execute your desired function
And, besides the conditions, it will sleep for 59 seconds
sleep(59);
(assuming your function it's a quick one). After the sleep, it will trigger itself usingfile_get_contents()
again.Important things to note:
- Create a way to interrupt the process (i.e. checking a value on the DB)
- Create a way to prevent 2 processes at same time
- On file_get_contents set the time limit on header to 2 or 3 seconds, otherwise the server may have various processes waiting for nothing
- You may want to use the
set_time_limit(90);
to try prevent server to break your function before the sleep
It's a solution, not a good one, and it may get blocked by the server. Using an external cron you can set a simple function and the server will use resources on it once at each 5 minutes. Using this solution, the server will be using resources on it all the time.
-
- 2017-09-05
Die Antwort von@johanoerklärt korrekt,wieein benutzerdefiniertes Intervallfür den WP-Cron-Jobeingerichtet wird. Die zweite Frage wirdjedochnichtbeantwortet. So wirdjede Minuteein Cron ausgeführt:
-
Fügen Siein der Datei
wp-config.php
denfolgenden Code hinzu:define('DISABLE_WP_CRON', true);
-
Fügen Sieeinen Cron-Job hinzu (
crontab -e
unter Unix/Linux):1 * * * * wget -q -O - http://example.com/wp-cron.php?doing_wp_cron
Dererste Teil (Schritt 1) deaktiviert deninternen Cron-Job von WordPress.Im zweiten Teil (Schritt 2) wird der WordPress-Cron-Jobjede Minutemanuell ausgeführt.
Mit der Antwort von @ Johano (wiemaneine Aufgabe alle 5 Minuten ausführt) undmeiner (wieman den Cronmanuell ausführt) sollten Siein der Lage sein,Ihr Ziel zuerreichen.
@johano's answer correctly explains how to set up a custom interval for WP cron job. The second question isn't answered though, which is how to run a cron every minute:
In the file
wp-config.php
, add the following code:define('DISABLE_WP_CRON', true);
Add a cron job (
crontab -e
on unix/linux):1 * * * * wget -q -O - http://example.com/wp-cron.php?doing_wp_cron
The first part (step 1) will disable WordPress internal cron job. The second part (step 2) will manually run WordPress cron job every minute.
With @Johano's answer (how to run a task every 5 minutes) and mine (how to manually run the cron), you should be able to achieve your goal.
Ich habeeine Funktion,die alle 5 Minuten ausgeführt wird. Ich habe aus dem Kodexfolgendes verwiesen:
Ichmöchte diese Funktionnur alle 5 Minuten ausführen,unabhängig davon,wannich anfangen soll. Wie kannich das?
Außerdem heißtesim Codex,dass cron ausgeführt wird,wennein Besucher die Sitebesucht. Gibteseine Möglichkeit,den Cron wiepro Minute zubetreiben undnicht aufeinen Besuch zu warten?
Nehmen wir an,diefolgende Funktion sollte alle 5 Minuten ausgeführt werden. Wie kannich das dannmit
?wp_schedule_event()
oderwp_cron
tun?