How Execute PHP File Using a Cron Job

混江龙づ霸主 提交于 2021-02-10 14:29:40

问题


I am using a WordPress site hosted on a DigitalOcean WordPress Litespeed droplet. I am attempting to run a php file in my theme every five minutes using a Cron Job. I don't want to use the default WordPress cron job system.

So far I have connected to the sever through ssh. Then entered the crontab using "crontab -e" then entered the following code then saved / exit

*/5 * * * * php /var/www/html/wp-content/themes/my_theme/cron.php

And inside the cron.php I put a simple mailing function for testing purposes:

<?php
    /*template name: Cron*/


    $content = date("h:i:sa");
    wp_mail( 'reece.r.barrett@gmail.com', 'Cron Test', $content, array());
?>

But I never receive an email so I assume its not working. Is there something wrong with the way I am declaring my cron job? Also I haven't disabled the WordPress Cron system like I have seen a lot of tutorials doing. Is this required to get my own cron to work?

This is how I've seen some tutorials disabling the WordPress cron in wp-config

define('DISABLE_WP_CRON', true);

回答1:


Your problem is that even if your file physically live inside your theme folder it is actually run "outside" wp core ENV since you are calling it directly. If you ask me, the best, simpliest and cleanest way to use external cron system inside WP ecosystem is to do something like this:

add_action( 'wp_ajax_nopriv_my_cron_action', array( 'myCronAction' ) );

function myCronAction(){
    //...your code
}

In that way you make use of WP ajax endpoint to enter the WP ecosystem. Be careful with security since in that way you are exposing a cron url to do your stuff. Securing that is up to you, but that's the easiest way to achieve that.

To use that from your cron you just need to make something that fetches an URL built like this: https://yourdomain.com/wp-admin/admin-ajax.php?action=my_cron_action

If you don't want to make it like that, then you have to bootstrap WP core yourself inside your .php file see https://wordpress.stackexchange.com/questions/47049/what-is-the-correct-way-to-use-wordpress-functions-outside-wordpress-files




回答2:


First check if your script run from cli/webhook. Then please check for cli execution, since there could be the case that php is not in server's PATH and you have to call full path to php, e.g.:

/usr/local/bin/php /home/your_username/public_html/path/to/cron/script.php


来源:https://stackoverflow.com/questions/64431018/how-execute-php-file-using-a-cron-job

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!