Comment exécuter une fonction toutes les 5 minutes?
-
-
Vousferiezmieux de regarderparexempleLinux cron ou des services crontiers si vous avezbesoin d'unintervalleet d'uneprécision aussi courts,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
-
le site a untraficimportant .. doncpasbesoin de considérer l'intervalle detemps .. sûr qu'il sera déclenchétoutes les 2 ou 3minutes.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
-
iln'estpaspossible de déclencher unfichierphp sans que quelque chosene tourne sur le serveur avec uneminuterie.its not possible to trigger a php file without something running on the server with a timer.
- 0
- 2015-11-10
- Andrew Welch
-
fichier?nousparlons d'unefonction dansfunctions.phpfile? we are talking about a function in functions.php
- 0
- 2015-11-10
- Foolish Coder
-
Pensez-vous qu'un service de surveillancegratuitpourrait être leping qui déclenche CRON?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 réponses
- votes
-
- 2016-01-29
Vouspouvez créer denouveaux horaires 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');
Vouspouvezmaintenantprogrammer votrefonction:
wp_schedule_event(time(), '5min', 'my_schedule_hook', $args);
Pourne leprogrammer qu'une seulefois,enveloppez-le dans unefonctionet vérifiez avant de l'exécuter:
$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'); }
Notez leparamètre $ args! Nepas spécifier leparamètre $ args dans wp_next_scheduled,mais avoir $ argspour wp_schedule_evententraînera laplanification d'unnombrepresqueinfini dumême événement (au lieu d'un seul).
Enfin,créez lafonction que vous souhaitezexécuter:
function my_schedule_hook(){ // codes go here }
Jepense qu'ilestimportant dementionner que wp-cron vérifie le calendrieret exécute lestâchesplanifiées à chaquefois qu'unepageest chargée.
Donc,si vous avez un site Web àfaibletrafic quin'a qu'un seul visiteurpar heure,wp-cronne fonctionnera que lorsque ce visiteurnaviguera sur votre site (unefoispar heure). Si vous avez un site àforttrafic avec des visiteurs demandant unepagetoutes les secondes,wp-cron sera déclenchétoutes les secondes,provoquant une charge supplémentaire sur le serveur.
La solutionest de désactiver wp-cronet de le déclencher via une véritabletâche cron dans l'intervalle detemps de votretâche wp-cronplanifiée à répétition laplus rapide (5min dans votre cas).
Lucas Rolff explique leproblèmeet donne la solutionen détail .
Vouspouvez également utiliser un servicetiersgratuittel que UptimeRobot pourinterroger votre site (et déclencher wp- cron)toutes les 5minutes,si vousne souhaitezpas désactiver wp-cronet le déclencher via un vraitravail cron.
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
Si votre site reçoit untraficimportant,vouspouvezessayer d'utiliser
set_transient()
pour l'exécuter (très approximativement)toutes les 5minutes,parexemple: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' ); }
-
Ehbien,euh,ouais?! ...Well, er, yeah?!...
- 0
- 2015-11-10
- bonger
-
ouais.,çane marche PAS ..j'ai utilisé le code suivant dans `functions.php` quand une visitefait sur lapage,unemise àjour serafaite à unetable dansmabase de données .. `function run_evry_five_minutes () {$ homepage=file_get_contents ('lien à visiter');echo $ homepage;} `.Mais latable DBn'estmêmepasmise àjour après 6minutes.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
-
Jene saispaspourquoi celane fonctionnepaspour vous,mais ypenser simplementen utilisant `get_transient ()`/`set_transient ()` sans lestrucs de cron abeaucoupplus de sens,beaucoupplus simple,mettra àjour la réponse ...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
-
@bongerest-ce unebonne alternative à wp_schedule_event ()?@bonger is this good alternative for wp_schedule_event() ?
- 0
- 2016-05-08
- Marko Kunic
-
@ MarkoKunić Jene saispaspour être honnête,je ne l'aipasessayé ... c'était seulementproposé comme solution de contournement,mais si vous l'essayez,faites-lenous savoir ...!(La réponse de Johano Fierra semblebonne 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
-
@bonger çamarche,mais c'est lamême chose,si vousn'êtespas sur le site Web,çane fonctionnerapas@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
-
Ehbien oui,commementionné à diversendroits sur cettepage,vous avezbesoin d'un vraitravail cron d'uneforme ou d'une autrepour lefaire sansnécessiter de visiteurs .... (mercipour le retour.)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
Vouspouvez le déclencher lors de l'activation duplugin au lieu de chaque appel deplugin:
//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
Je crains qu'àpart attendre que quelqu'un visite votre site quiexécute unefonction,la seule autre option consiste à configurer unetâche cron sur votre serveuren utilisant quelque chose comme ceci https://stackoverflow.com/questions/878600/how-to-create-cronjob-using-bash ou si vousavoir uneinterface de style cpanel sur votre serveur,parfoisil y a uneinterfacegraphiquepour la configurer.
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.
-
ouais,.,je comprends cela .. J'ai déjà quelques crons créés àpartir de cPnael ..maismaintenantj'essaye d'exécuter unefonction àpartir de `functions.php`parce que lorsque lafonctionest dans un`plugin` ou dans `functions.php`nousne pouvonspas demander aux clients de configurereux-mêmes un cron depuis cpanel.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
Leplugin Cronjob Scheduler vouspermet d'exécuter destâchesfréquentes demanièrefiableet rapide sans quepersonnen'ait à lefairevisitez votre site,tout ce dont vous avezbesoinest aumoins 1 actionet un calendrier Unix Crontab.
Ilesttrèsfacile à utiliseret trèsflexible.Vous créez votreproprefonctionet définissez une actionen son sein.Ensuite,vouspouvez choisir votre action dans lemenu dupluginet la déclencher quand vous le souhaitez.
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
J'ai une solutionpossibleen utilisant unefonction deplanificationet unefonction récursive WP Ajax.
- Créer un événement deplanification de 60minutespourexécuter unefonction
- Cettefonction déclenchera unefonction récursive utilisant Ajax via
file_get_contents()
- Lafonction ajax aura un compteur sur labase de données avec unnombretotal de 60 (pour chaqueminute à l'intérieur de l'heure).
- Cettefonction ajax vérifiera votre compteurpour:
Si le compteurest égal ou supérieur à 60,il réinitialisera le compteuret attendra laprochainetâche cron.
Si le compteurestmultiple de 5 (donctoutes les 5minutes),ilexécutera lafonction souhaitée
Et,en plus des conditions,il dormirapendant 59 secondes
sleep(59);
(en supposant que votrefonction soit rapide). Après le sommeil,il se déclencheraen utilisant ànouveaufile_get_contents()
.Pointsimportants ànoter:
- Créer unmoyen d'interrompre leprocessus (c'est-à-dire vérifier une valeur sur labase de données)
- Créer unmoyen d'empêcher 2processusen mêmetemps
- Surfile_get_contents,définissez la limite detemps sur l'en-tête à 2 ou 3 secondes,sinon le serveurpeut avoir diversprocessus quin'attendent rien
- Vous voudrezpeut-être utiliser le
set_time_limit(90);
pouressayer d'empêcher le serveur d'interrompre votrefonction avant le sommeil
C'est une solution,pas unebonne,et ellepeut êtrebloquéepar le serveur. En utilisant un cronexterne,vouspouvez définir unefonction simpleet le serveur utilisera les ressources dessus unefoistoutes les 5minutes. En utilisant cette solution,le serveur utilisera des ressources dessustout letemps.
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
La réponse de@johanoexplique correctement comment configurer unintervallepersonnalisépour latâche cron WP. La deuxième question reste cependant sans réponse,à savoir commentexécuter un crontoutes lesminutes:
-
Dans lefichier
wp-config.php
,ajoutez le code suivant:define('DISABLE_WP_CRON', true);
-
Ajouter unetâche cron (
crontab -e
sous unix/linux):1 * * * * wget -q -O - http://example.com/wp-cron.php?doing_wp_cron
Lapremièrepartie (étape 1) désactivera letravail croninterne de WordPress.La deuxièmepartie (étape 2)exécuteramanuellement letravail cron WordPresstoutes lesminutes.
Avec la réponse de @ Johano (commentexécuter unetâchetoutes les 5minutes)et lamienne (commentexécutermanuellement le cron),vous devriez êtreen mesure d'atteindre votre objectif.
@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.
J'ai unefonction àexécutertoutes les 5minutes. J'aifait référence à la suite du codex:
Je souhaiteexécuter cettefonctiontoutes les 5minutes,quel que soit lemoment de démarrage. Commentpuis-je cela?
Ilindique également que le codexindique que cron seraexécuté lorsqu'un visiteur visite le site. Existe-t-il unmoyen d'exécuter le cron aubout de quelquesminutes sans attendre une visite?
disons que lafonction suivante doit êtreexécutéetoutes les 5minutes,commentpuis-je lefaireen utilisant
wp_schedule_event()
ouwp_cron
?