首页 文章

在unix cron中调用php中的函数

提问于
浏览
1

我有一个wordpress网站 .

我在以下目录中有一个php文件 "test.php"

/var/www/html/wp-content/themes/some_theme/parts/cron

test.php 只有一个功能:

function cron_test(){
   error_log( print_r( "It works" ) ); //print to debug.log
};

What I want:

使用 sshcrontab -e ,我想添加一个cronjob来调用这个函数 .

What I did: 我尝试了不同的cron套件,看看哪些有效

*/2 * * * * /usr/bin/php /var/www/html/wp-content/themes/some_theme/parts/cron/test.php -f cron_test> /dev/null 2>&1
*/2 * * * * /usr/bin/php /var/www/html/wp-content/themes/some_theme/parts/cron/test.php cron_test> /dev/null 2>&1
*/2 * * * * /usr/bin/php /var/www/html/wp-content/themes/some_theme/parts/cron/test.php > /dev/null 2>&1
*/2 * * * * /usr/bin/php -q /var/www/html/wp-content/themes/some_theme/parts/cron/test.php cron_test> /dev/null 2>&1
*/2 * * * * /usr/bin/php -q /var/www/html/wp-content/themes/some_theme/parts/cron/test.php -f cron_test> /dev/null 2>&1
*/2 * * * * /usr/bin/php -q /var/www/html/wp-content/themes/some_theme/parts/cron/test.php /dev/null 2>&1

当然,它们都没有奏效 .

我错过了什么?我怎么能调用这个函数?

谢谢!

2 回答

  • 3

    几个月前我遇到了这个问题 . 为了解决这个问题,我创建了一个简单的sh脚本来调用我的php页面,然后我将脚本调用到我的crontab中 .

    crontab:

    40 22 * * * sh /.../updateAvai.sh /.../lastUpdateAvai.log
    

    updateAvai.sh:

    #! /bin/bash
    
    php /.../genereListe.php
    
    cat /.../liste | while read LINE
    do
    php /.../lineTask.php $LINE > /dev/null 2>&1
    done
    

    lineTask.php:

    #!/usr/local/bin/php
    
    <?php
    
    ...
    // $argv[1] contains the first argument
    echo " arg " . $argv[1] . " " . (new \DateTime())->format("Y-m-d H:m:s") . "\n";
    ...
    
    ?>
    

    希望能帮助到你,

    吕克 .

  • 0

    @ user1597430你能举个例子吗?谢谢!

    样品电话: php test.php init

    示例代码:

    <?php
    
    switch ($argv[1])
    {
        case 'init':
            cron_test();
    }
    
    function cron_test(){
       error_log( print_r( "It works" ) ); //print to debug.log
    };
    

    实际上,这是一种来自C语言的经典方式,如果你google argv / argc ,你可能会获得更多信息 .

相关问题