如何使用zend框架2运行cron作业

时间:2013-11-03 10:51:04

标签: php cron zend-framework2

我在Zend Framework 2中内置了应用程序。我想设置cron作业来更新我的产品。我知道这样的脚本应该从公共文件夹外部运行,但不幸的是我在cron中的脚本需要使用框架文件。
我怎么能这样做?
我想出的唯一方法是从公共文件夹外部运行脚本然后添加一些哈希或密码并重定向到

www.domain.com/cron/test

所以我将拥有所有框架功能 它会安全吗?也许还有另一种方式?

2 个答案:

答案 0 :(得分:24)

我强烈建议您使用CLI来满足此类要求。

  1. 在应用程序模块中创建一个带有updateAction()的ConsoleController。
  2. console route添加到您的应用程序模块的module.config.php

    array(
        'router' => array(
            'routes' => array(
            ...
            )
        ),
    
    'console' => array(
        'router' => array(
            'routes' => array(
                'cronroute' => array(
                    'options' => array(
                        'route'    => 'updateproducts',
                        'defaults' => array(
                            'controller' => 'Application\Controller\Console',
                            'action' => 'update'
                        )
                    )
                )
            )
        )
    )
    );
    
  3. 现在打开终端并

    $ cd /path/to/your/project
    $ php public/index.php updateproducts
    
  4. 多数民众赞成。希望它有所帮助。

答案 1 :(得分:2)

我在collabnet找到了解决方案(现在已经死了)。

我在这里复制解决方案,因为ColabEdit有时会删除帖子:

<?php
/*
Cron directory setup:

Cron
    config
        module.config.php
    src
        Cron
            Controller
                IndexController.php
    autoload_classmap.php
    Module.php                

NOTES: Remember to include the Cron module in the main config file (trunk/config/application.config.php)

Once you have the route in place, write your cron and call it from your webhost cron manager.

*/

// Cron/config/module.config.php
return array(
    // Placeholder for console routes
    'controllers' => array(
        'invokables' => array(
            'Cron\Controller\IndexController' => 'Cron\Controller\IndexController'
        ),
    ),
    'console' => array(
        'router' => array(
            'routes' => array(
                //CRON RESULTS SCRAPER
                'my-first-route' => array(
                    'type'    => 'simple',       // <- simple route is created by default, we can skip that
                    'options' => array(
                    'route'    => 'hello',
                    'defaults' => array(
                        'controller' => 'Cron\Controller\IndexController',
                        'action'     => 'index'
                        )
                    )
                )

            ),
        ),
    ),


);

<?php
// Cron/src/Cron/Controller/IndexController.php
namespace Cron\Controller;

use Zend\Mvc\Controller\AbstractActionController;

class IndexController extends AbstractActionControlle
{
    public function indexAction()
    {
        echo "hello";
        echo "\r\n";
    }
}

From the console navigate to trunk (or public_html) (the directory before public) and run:

path/to/trunk>php public/index.php hello

hello
path/to/trunk>
相关问题